Reputation: 6574
hi all i've got this bit of code but it keeps kicking out 'undefined;
var projectID = $.getUrlVar('id');
var projectname;
$.get('functions.php?func=projectname&id='+projectID, function(data) {
projectname = data;
alert(projectname+'<- see nice content');
});
alert(projectname+'<- no content :(');
how can i make "projectname" available outside that one get function?
(i did notice, when running that code actually, that the no content alert popped up before the nice content. is the .get the last thing on the page that runs? is this why its all blank? coz the variable doesnt appear to be set yet?
thanks
Upvotes: 1
Views: 69
Reputation: 490243
Because the XHR is asynchronous, you can't like that.
Handle all code as a descendent function, deeper on the callstack with an origination from the complete callback (where projectname
will have the correct value assigned).
Upvotes: 0
Reputation: 254926
AJAX runs asynchronously (that is what first A
in AJAX
acronym stands for).
So you have 2 solutions for your issue:
$.get
to $.ajax
and set its async
option to false (terrible solution)Upvotes: 5
Reputation: 164776
The problem here is that your second alert actually executes before the AJAX request has finished.
The "A" in "AJAX" stands for Asynchronous.
Any functionality relying on data returned from an AJAX request should only be implemented within or called by the success
callback
Upvotes: 2