JQuery Passing a variable from one function to another function

I need to create a variable and assign a value to this variable for use later. To save complexity and keep it simple, I deleted the details, which are also part of what else is included in var item2. The variable in this example will be mySeries

var mySeries;

$.getJSON("/_scripts/proxy.php", jsonObj, function(item)
{
//Stuff happens here

//NEED TO ASSIGN VALUE TO mySeries HERE:
mySeries = item[0].series_id;

//Stuff happens here
});

//NEED TO USER mySeries VALUE HERE BUT IT IS NOT DEFINED
var item2 = mySeries;
+3
source share
3 answers

With ajax, you need to use callbacks, since ajax asynchronous:

$.getJSON("/_scripts/proxy.php", jsonObj, function(item)
{
   var mySeries;
   //Stuff happens here

   //NEED TO ASSIGN VALUE TO mySeries HERE:
   mySeries = item[0].series_id;
   save_series(mySeries)
   //Stuff happens here
});

function save_series(s){

   var item2 = mySeries;

   //...etc
}
+3
source

mySeries gets assigned AFTER the json request completes, your item2 gets assigned before it completes.

0
source

, , item2, , , , . .ajax() , .

0

All Articles