1

I am trying to populate am empty object with data being returned from a POST request. The data is being returned successfully, but in the code the object is found to be null. The code is given below:

var item = {};   
var args= {p: "<?php echo $id; ?>"};

$.post('api.php', args, function(response) {

    startSpinner(spinner);
    if (response.status == 0) {
        item = response.data;
        console.log("ITEM: " + JSON.stringify(item));
    }

}).done(function() {
    ..
});

if (item == null || item == undefined) {
    alert("TTEMST");
}

In the console log, the item is clearly being shown to get populated with data, but the if condition for a null object is somehow being satisfied, i.e. the alert box is being displayed. I think there is something wrong with the way I am populating the object. Please help!!

user3033194
  • 1,775
  • 7
  • 42
  • 63

3 Answers3

2

$.post() is asynchronous. alert execute before your success callback

gzc
  • 8,180
  • 8
  • 42
  • 62
1

This line of code will most likely run before the post returns. You should add that to the callback or the then. The code will not wait for $.post to return before moving to that if statement.

if (item == null || item == undefined) {
    alert("TTEMST");
}
AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43
1

Your if condition, which has alert won't wait for the Post to complete.

You need that if inside the callback of post, like this:

$.post('api.php', args, function(response) {

    startSpinner(spinner);
    if (response.status == 0) {
        item = response.data;
        console.log("ITEM: " + JSON.stringify(item));

        if (item == null || item == undefined) {
            alert("TTEMST");
        }
    }
Aragorn
  • 5,021
  • 5
  • 26
  • 37