Save response from $ .get in a variable that will be used later

I get a response from php with $ .get, but how to save the response in a variable so that I can use it later in my code? Thanks!

$.get('promo_getstate.php', { email: emailaddress, country: 'DE', lang: lang, source: '1304_Spring_dly' }, function (data) { console.log('data is' + data); getstate = data; }); 
+4
source share
5 answers

just declare the variable you want to set outside of the .get call itself. then it will be available inside the callback function, where you want to set it to the returned data.

 var getstate = ""; $.get('promo_getstate.php', { email: emailaddress, country: 'DE', lang: lang, source: '1304_Spring_dly' }, function (data) { console.log('data is' + data); getstate = data; }); 
+5
source

You need to make sure that the destination can be accessible outside the scope of the outgoing call.

If getstate not declared outside the request for receipt, it will not be available for subsequent calls.

Question: when or in what area do you need this data?

You can simply place it under the window area. Although it is bad practice to put everything under the global scope, it will give you an idea of ​​where to put it.

 console.log('data is' + data); window.getstate = data; 

Now, at any time after its appointment, it will be available through window.getstate or just getstate .

0
source

Try saving $.get() in a variable:

 var myVar = $.get('promo_getstate.php', { email: emailaddress, ......... }); 
0
source

How $ .get works, the browser still receives data, and also processes strings after $ .get.

 $document.ready(function() { var $HTML=""; //global variable $(".button").click(function(event){ console.log('before $.get: '); $.get('form1.html #form1', function(data){ $HTML = data; console.log('inside $.get: ' + $HTML); }); console.log('outside $.get: ' + $HTML); }); 

So the solution is that all the code that needs the $ .get value must go into the get statement.
Or you can somehow wait until the result returns and the $ .get code is complete before processing the lines after

0
source

The best solution is to use

 setTimeout(function(){ console.log('outside $.get: ' + $HTML); }, 100); 
0
source

All Articles