Reputation: 16299
That title was a mouthful. Here's what I'm trying to do in code below. The callback in this case is in the jQuery $.get function.
function getMapMarkup(loadUrl, myVar) {
me = myVar;
$.get(
loadUrl,
{ var1: "hello", var2: "world" },
function(responseText) {
me = responseText;
myVar = me; //doesn't work.
},
"html"
);
}
Is there a way to change the value of myVar
in the function(responseText)
callback, so I can use it in my program later on? Or is there another (better) way to go about what I'm trying to do?
Upvotes: 0
Views: 111
Reputation: 79830
Most likely you are accessing myVar
before the callback is executed.
$.get
makes an AJAX call which is asynchronous and so the callback function will be called later after your server responded and so any immediate access to myVar
will not have the updated value.
Upvotes: 1
Reputation: 1038720
If by later on
you mean immediately after the $.get
call then no, there is no way because AJAX is asynchronous and the $.get
returns immediately and the success callback can be executed much later. The only reliable way to know when this happens is to put the code that depends on its result inside the success
callback. You could also call some other function inside the success callback passing it the result of the AJAX call.
Upvotes: 2