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; })
l(session);
// *all XHR flags in an object, responseText ("EYES!!"), status (200) etc.


$.get("item.php", function(data) { session = data; })
l(session);
 // 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)

l(session);
// "EYES!!"
Member Avatar for 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.