l(x) is my shortcut to console.log(x). item.php has text "EYES!!", just that.

var session = $.get("item.php", function(data) { session = data; })
// *all XHR flags in an object, responseText ("EYES!!"), status (200) etc.

$.get("item.php", function(data) { session = data; })
 // undefined

$.get("item.php", function(data) { l(data) })
// "EYES!!"

(note, these are 3 different cases, but I cannot them get seperated without HTML freaking out)
Is there a way for me to transfer $.get response into external variable? Code generally looks something like this:

var session;

(need some fairy magic to happen)

// "EYES!!"

Edited by pritaeas: Moved to web dev.

1 Year
Discussion Span
Last Post by stbuchok

Your $.get calls are all asynchronous calls.

Line 1. you declare a variable called session, it is set to undefined right away because $.get is a function that doesn't have a return value and all functions return undefined if there is no return statement. Before the callback happens, we go down and execute line 2 (because it is async).

Line 2. session is still undefined, because the $.get function returns undefined (look above) and the async call has not completed and the callback to set session = data has not happened yet.

Line 6. Same thing. You are making an async call to a web service.

Line 7. The async call from the two previous async calls have not completed and session is still set to undefined.

Line 12. You are using the callback to log the value.

If the call absolutely needs to be synchronous, jQuery has settings to make it a synchornous webservice call rather than asynchronous.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.