Lusine Martirosyan
Lusine Martirosyan

Reputation: 79

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

Upvotes: 2

Views: 34565

Answers (5)

Rockrahu001
Rockrahu001

Reputation: 81

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;

    }
});

Upvotes: 1

Justin Farrugia
Justin Farrugia

Reputation: 124

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.

Upvotes: 1

gre_gor
gre_gor

Reputation: 6787

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]);
    }
});

Upvotes: 0

Amr Magdy
Amr Magdy

Reputation: 1818

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]);

Upvotes: 5

Shemil R
Shemil R

Reputation: 49

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

Upvotes: 0

Related Questions