2

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

Lusine Martirosyan
  • 79
  • 1
  • 5
  • 14
  • 1
    Possible duplicate of [jQuery: Return data after ajax call success](http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success) – vaso123 Sep 22 '16 at 11:28
  • u can declare getdata array globally means staring of the script then it will be available outside the function – The developer Sep 22 '16 at 11:43

5 Answers5

5

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]);
Amr Magdy
  • 1,710
  • 11
  • 13
1

You have to declare that variable getData[name] above the ajax call so you can value after it.

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

    }
});
ahmedg
  • 309
  • 1
  • 2
  • 12
1

async false should be avoided. Play along the async and use events like .done to handle the response. This makes sure that the response is handled irrelevant of where the control is at the time of the callback. You don't care.

0

Use the property 'async:flase' in code and try once

Shemil R
  • 49
  • 6
0

AJAX stands for

asynchronous JavaScript and XML.

When you call alert the AJAX call isn't finished, that's why getData[name] isn't set.

You have to call alert (or do anything with it) inside the success callback.

$.ajax({
    type: 'GET',
    url: url,
    dataType: 'json',
    success: function (response) {
         getData[name] = response;
         alert(getData[name]);
    }
});
gre_gor
  • 6,669
  • 9
  • 47
  • 52