Monday, 8 August 2016

ajax - Getting variable value from $.each anonymous function




This is my AJAX success callback:




success: function(data){
var uD = '
    ';
    $.each(data['user details'], (function(key,val){
    uD += '
  • ' + val + '
  • ';
    });
    uD += '
';
return uD;
}



data is a JSON object.



As you can see, I'm trying to build a list out of the JSON object, but by the time I return the variable uD, it's undefined. How can I get the value of uD past the scope of the $.each function?



Edit: Sorry, I should have specified. The return statement was only in the AJAX callback because the AJAX call is within another function (which needs to return something.) Since it's async, I couldn't return 'after' the AJAX call, it had to be in the callback.


Answer



From an Ajax callback, you cannot return data. I guess you want to insert the UL you have built into the DOM, so you should do it inside your Ajax callback function.



success: function(data){

var uD = '
    ';
    $.each(data['user details'], (function(key,val){
    uD += '
  • ' + val + '
  • ';
    });
    uD += '
';
$('body').append(uD);
}


Instead of body specify the element you want to insert it into or use any other DOM Insertion functions.




With asynchronous AJAX calls you cannot really return things. So you cannot do things like



function GetMyList() {
//AJAX CALL
//RETURN RESULT OF AJAX CALL
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...