user1184100
user1184100

Reputation: 6894

Object reference error after ajax success operation - jquery

In above ajax call the object jData returns null .. but returns the object successfully if displayed with success:

var jData = null;

function x() {

$.ajax({
url : 'http://...",
success : function(data) {
    jData = data;
    alert(jData);   // displays the object
}


});
 return jData;  //returns null ??
};

Upvotes: 1

Views: 585

Answers (3)

Kunal Vashist
Kunal Vashist

Reputation: 2471

Your are getting the data out of the scope of your block , that for very reason it not occuring ,, return your jdata inside the success operation

Upvotes: 1

jbabey
jbabey

Reputation: 46647

Ajax is asynchronous, you need to return jdata from inside the success callback. Otherwise when you return jdata, the ajax call has not yet returned and jdata has not been assigned a value.

Upvotes: 0

Martin.
Martin.

Reputation: 10539

$.ajax() is asynchronous. You have to work with jData directly in success callback

var jData = null;

function x() {
    $.ajax({
       url : "http://...",
       success : function(data) {
          jData = data;
          alert(jData);   // displays the object
          //do stuff here
       }    
    });
}

Upvotes: 1

Related Questions