Lusine Martirosyan Lusine Martirosyan - 2 months ago 7
jQuery Question

How to use response data from ajax success function out of Ajax call

I have question, When I make ajax call, and in success function I get json data, I can't use it out of success function

$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function (response) {
getData[name] = response;

}
});
alert(getData[name]);


My question is how to work with getData out of ajax call

Answer

The problem is that by default Ajax request is async
which means that ajax will start the request then execute: alert(getData[name]); then finish the request in the background and call success function.

so actually the alert will execute before success function. and to do what you want you have to tell ajax not to execute any thing before it done, in other ward set async: false
Second thing you have to declare the variable outside the ajax scope so you can access it outside ajax

The final code will be :

var getData;
$.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        async: false,
        success: function (response) {
            getData[name] = response;

        }
    });
 alert(getData[name]);
Comments