Context
I have a function that is called within an AJAX call that returns a number. I set this number to a variable and want to access the number outside of the .done()
method:
$.ajax({
url: 'urlhere.php',
type: 'GET',
data: {text: text},
success: function(data) {
var getNumber = countNumber();
getNumber.done(function(data) {
var number = data;
});
let newContent =
"The number is "+
number;
}
});
But I get this error, stating that the variable is not defined:
Uncaught ReferenceError: number is not defined
Question
How do I access variables within the .done()
method in jQuery in an AJAX call?
Things I Have Tried
I have already tried defining the variable before the function call and then changing it in the done()
method, like so:
var number; //initialize variable
$.ajax({
url: 'urlhere.php',
type: 'GET',
data: {text: text},
success: function(data) {
var getNumber = countNumber();
getNumber.done(function(data) {
number = data;
});
let newContent =
"The number is "+
number; //console.log's "undefined"
}
});
This only makes the variable equal to undefined
, so I don’t think anything inside the done()
method is able to change existing variables. Any ideas? Let me know if there is any confusion. Thanks.
2
Answers
It seems
getNumber.done()
is asyncronous. Which means it takes a while to update the the value ofnumber
;You may do this:
Your problem is that the code is asynchronous so the number variable won’t be assigned just after you can the done() function.
What you can do:
Something like this: