Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX- response data not saved to global scope?

Tags:

jquery

scope

ajax

I am having the issue of my below shown lines not storing the variable into the global scope:

var somedata;

$.ajax({
    cache: false,
    url: verification_url,
    success: function(data){
        somedata = data;
    }
});

alert(somedata); // Undefined

What am I doing wrong? Do I need to wrap this into a separate function or what?

like image 708
Industrial Avatar asked Dec 05 '22 21:12

Industrial


2 Answers

The alert() code runs before the response from $.ajax is received.

That's why it's undefined.

var somedata;

$.ajax({
    cache: false,
    url: verification_url,
    success: function(data){
        somedata = data;

        alert( somedata );   // 2. this will occur after the response is received
    }
});

alert(somedata); // 1. this will occur first

Here you can see that the alerts happen out of order. By default an AJAX request does not prevent subsequent code from running.

That's the entire purpose of having a callback method. It is a method that gets called at the appropriate time, instead of relying on synchronous execution.

like image 133
user113716 Avatar answered Dec 07 '22 10:12

user113716


AJAX is asynchronous. That's what the A stands for in the acronym. You can access the results only in the success callback:

$.ajax({
    cache: false,
    url: verification_url,
    success: function(data){
        // HERE AND ONLY HERE YOU HAVE THE RESULTS
        // So it is here that you should manipulate them
        alert(data);
    }
});

// this line is executed MUCH BEFORE the success callback 
// and the server hasn't yet sent any response.

So any code that needs to manipulate the results must be place inside the success callback or in a function which is invoked from the success callback. You should not be relying on global state for this pattern.

like image 29
Darin Dimitrov Avatar answered Dec 07 '22 09:12

Darin Dimitrov