VinsMat VinsMat - 1 month ago 6
Ajax Question

Empty return in ajax call if I call a method inside

I would like to ask a question about a problem in ajax:

$.ajax({
url: "wikiLoader.php?keyword=" + nomeRicerca+"&username="+nomeUtente,
type: 'GET',
contentType: "application/json",
dataType: "json",
success: function(res) {
console.log(res);
content.annotator("loadAnnotations", res);
},
error: function(xhr, textStatus, error) {
...
}
});


In my console res is empty when I print it, but inside the function content.annotator("loadAnnotations", res) it works well and res infact is not empty. If I comment the function content.annotator("loadAnnotations", res) I see the real content of res that is a json object
Thank you in advance for the answer

Answer Source

The AJAX call is still being executed as your code moves on to the console.log(res) line, so the message variable has no value.

You need to pass the value of the response to a function within the success method.

success: function(res) {
  printValue(res);
}

// outside AJAX call

function printValue(res) {
    console.log(res);
    var content = res;
    content.annotator("loadAnnotations", content);
}