I have the following jQuery Function. I’m trying to return the GUID value shown here in the alert(); The alert works fine and the value is populated, however I can’t seem to assign it to a variable and return its value.
Ultimately I need to access the GUID value in other functions, etc. Everything I’ve tried only displays as undefined.
I’d like to do something like this:
function trackPage(){
var elqTracker = new jQuery.elq(459);
elqTracker.pageTrack({
success: function() {
elqTracker.getGUID(function(guid) {
alert(guid);
var returnValue = guid;
});
}
});
return returnValue;
}
var someGuid = trackPage();
So, this question has been asked a million times over, and I’m sure that everyone (myself included) tried this once.
It is just the nature of an asynchronous call, you can’t use their results as a
returnvalue. Thats why they have you passing in a function that gets the result of the call, they can’treturnit either! Also notice that theelqTracker.pageTrack()function call returns IMMEDIATELY, therefore yourreturnValueis simplyundefined.Most people (see dfsq’s answer) solve this problem by introducing a callback function as a paramater. This method is tried, and true – however jQuery has
$.Deferred. This allows you to make your own asynchronous logic return apromisewhich you can then attach any number of callbacks to:Notice now that your
trackPage()returns an object that you can attach callbacks to? You don’t have to attach them immediately either.Also, the jQuery AJAX module always returns promises as well, so the interface for all your AJAX stuff should be very similar if you make your own logic return promises.
As a side note: I’d like to point out that your
var returnValuewas in the wrong “scope” anyway. It needed to be declared in the outer scope of thetrackPagefunction. Even with this fix, the concept still doesn’t work.