0
var transactionID;
$.get('http://127.0.0.1/getId', null,function(data) {
    transactionID = data;
    alert(transactionID);
});
alert(transactionID);

The alert inside the get method returns value correctly. However, when the transactionID in the 2nd alert outside of the get method is still null? How to correctly pass out the return data from the get method?

domdomcodecode
  • 2,355
  • 4
  • 19
  • 27
vaj oja
  • 1,151
  • 2
  • 16
  • 47
  • That is because of the flow of control in javascript. To get the transactionID correctly you should be using the get inside a callback function. –  Mar 20 '14 at 10:21

1 Answers1

1

The $.get is executed asynchronously, i.e. it sends the request to the server and executes the lines after it. So the alert outside will be executed before the server returns the reply, and when it does it will execute the function in the get method.

In order to use the returned value, place any needed code inside the get call, for example call another function passing it the transactionID as an argument:

var transactionID;
$.get('http://127.0.0.1/getId', null,function(data) {
    transactionID = data;
    alert(transactionID);
    doSomethingWithID(transactionID);
});

Or just call a function the uses it:

$.get('http://127.0.0.1/getId', null,function(data) {
    transactionID = data;
    alert(transactionID);
    doSomethingWithID();
});
function doSomethingWithID()
{
  // code that uses transationID
}
Sari Alalem
  • 870
  • 7
  • 18
  • Thanks for the comments. However, i need to set the global variable and can't place all the methods inside that get method. Is there a way to do this? – vaj oja Mar 21 '14 at 02:19
  • You are already setting the global variable's value, but the issue is that you need to access it after you set its value, and its guaranteed to be set only after the the response from the server returns. You don't have to place all the methods inside the get method, you just need the get method to tell when the value is set, for example have a boolean variable that is set to true when the get is done, and the code will keep waiting until this value is true. But I wouldn't go that way. – Sari Alalem Mar 23 '14 at 09:00