0

I want to save the value of data and status in a variable and use it after the closing brackets of jquery GET/POST function.But alert comes only when it is inside .get braces.

$(document).ready(function(){
    $.get("demo_test.asp",function(data,status){
         v = data;
     });
 alert("Data:"+v);
 });
Michael
  • 1
  • 1
  • 2
  • 2
    You are creating a global variable (`v`) which can be accessed from anywhere in your JS. You however won't have a global `v` variable accessible until the AJAX response is received. Your `alert` will fire before the AJAX response is received so the above example should return `Data:undefined`. – Jasper Sep 27 '13 at 16:07
  • `$.get("demo_test.asp",function(data,status){ v = data; }).done(function(){alert("Data:"+v);});` – A. Wolff Sep 27 '13 at 16:11
  • 1
    possible duplicate of [How to return AJAX response Text?](http://stackoverflow.com/questions/1225667/how-to-return-ajax-response-text) – Quentin Sep 27 '13 at 16:14

3 Answers3

1

As Jasper said, your alert is being triggered before the request is complete (async!). So, you have two options:

Do your logic inside the callback:

$.get("demo_test.asp",function(data,status){
     v = data;
     alert("Data:"+v);
     //Process stuff here
});

Or pass the received data onto another function and work with it there

$.get("demo_test.asp",function(data,status){
     v = data;
     doStuff(v);
});

function doStuff(param) {
    console.log(param);
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

You're absolutely correct; the code is working as it should... here's why:

The page loads and starts running code, it then hits the .get command and then keeps running, obviously making it to the 'alert' you have next. Since the .get function is still working on fetching the data before your page makes it to the 'alert' part... there's nothing to prompt.

You might want to string things together after the .get, using deferred objects. Look into: http://api.jquery.com/deferred.always/

This is a way of tacking on another function inside of the one fetching your data, so they depend on each other.

RomoCode
  • 1,099
  • 9
  • 17
0

Simple answer, yes, you can store the data in a global variable and access it elsewhere. However, you must wait until it is ready.

The better way to do it is to instead store the jqXHR globally and simply add a done callback to it when you need to access the data.

var reqDemoTest = $.get(...);
//... some time later...
reqDemoTest.done(function(data){
    console.log(data);
});
Kevin B
  • 94,570
  • 16
  • 163
  • 180