Sarah
Sarah

Reputation: 119

Replace 'null' values from AJAX call

I have an AJAX call which gets time (in minutes) from a database. However, if the value fetched from the database is null, I want to replace "null" to show "0 minutes". Right now, it doesn't display anything if the time is null.

$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$(function() {
    $.getJSON($SCRIPT_ROOT + '/_ajax',
    function(data) {
        $("#timePeriod").text(data.timePeriod);
        if (data.timePeriod == null) {
            data.timePeriod = '0';
        }
    });
});

This is then displayed in the HTML using the following span tag:

Average time: <span id="timePeriod"></span> mins

The if statement in my AJAX code doesn't work as intended. It doesn't display anything (not even null, although that is what's being returned). How can I properly replace this value so that it displays a '0' when the result is null?

Upvotes: 0

Views: 1245

Answers (2)

nanobar
nanobar

Reputation: 66355

document.getElementById('timePeriod').innerText = +data.timePeriod

Using + converts to a number, +null is already 0.

document.getElementById('timePeriod').innerText = +null
Average time: <span id="timePeriod"></span> mins

Upvotes: 2

briosheje
briosheje

Reputation: 7446

If I understood the problem properly (despite I'm not really aware why you are using data.wait), it should be as easy as:

data.timePeriod = !isNaN(+data.timePeriod) ? +data.timePeriod : '0';
$("#timePeriod").text(data.timePeriod);

Explanation:

(Logically) you want to check whether the data you are receiving is valid. It may be null (sure), but it also may hold any other strange value. So, to be 100% sure that the value actually can be parsed, we firstly try to cast it to a number (using the unary operator +), then we check whether it's NOT a NaN: !isNan, the evaluation will return true if the the result effectively is a number.

If it is, it assigns the value to the data object, else it assigns '0'.

The second line just put the value in the span element.

Upvotes: 3

Related Questions