Passible To Pass $.ajax Inside Variable Value To Global?
Solution 1:
There are two problems here:
Inside your success handler, you are redefining test
with the var
keyword. This is now using a new variable named test
that is scoped for just your success handler.
Remove the var
keyword. Then it will look for a variable named test
in the outer scope, searching progressively outward until it either finds a variable named test
, or fails to find one in which case it will create a new variable attached to window
.
Your second problem is that ajax is asynchronous by default. That means it would not be calling test = true
until all of the subsequent code has finished running. If you are examining the value of test
immediately after the ajax
call, then it will be undefined
because the done
hasn't been called yet.
For this simple example, make the call synchronous, by setting the async
property to false.
// Do you want to use the text within this scope?// If not, remove this declaration, and then it really will be// window.testvar test;
$('button').on('click', 'loader', function(){
$.ajax({
url: 'www.myweb.com/string/index.html',
type: 'get',
async: false,
dataType: 'html'
}).done(function() {
test = true;
}).fail(function() {
test = false;
});
Solution 2:
Just don't use the var
keyword inside the ajax callbacks when setting test
's value.
Post a Comment for "Passible To Pass $.ajax Inside Variable Value To Global?"