Reputation: 19425
I thought I knew how this worked - obviously not.
I'm not able to return a value gotten from a jQuery Ajax request.
This is my code:
function initForm() {
prefix = getPrefix(country_id);
alert(prefix); // <-- prefix is empty
}
// Get prefix
function getPrefix(country_id) {
var prefix = '';
jQuery.ajax({
url: siteURL +"/wp-content/themes/storelocator/include/jquery.php",
data: {instance: 'getPrefix', country_id : country_id},
success: (function(data) {
prefix = data.prefix;
alert(prefix) // <--- This alerts correct value
}),
dataType: 'json'
});
return prefix; // <-- This value is not set
}
How do I use callback correctly to set the prefix
variable inside the jQuery.ajax
call?
Upvotes: 0
Views: 283
Reputation: 139
An alternative, while not recommended is to use to synchronized version.
jQuery.ajax({
url: siteURL +"/wp-content/themes/storelocator/include/jquery.php",
data: {instance: 'getPrefix', country_id : country_id},
success: (function(data) {
prefix = data.prefix;
alert(prefix) // <--- This alerts correct value
}),
async:false,
dataType: 'json'
});
But I would concur with the previous answers.
Upvotes: 0
Reputation: 4329
This may work for you. Since Ajax calls are asynchronous, you need to have a callback to set the prefix variable.
function initForm() {
getPrefix(country_id);
}
function getPrefix(country_id) {
var _this=this;
jQuery.ajax({
url: siteURL +"/wp-content/themes/storelocator/include/jquery.php",
data: {instance: 'getPrefix', country_id : country_id},
success: (function(data) {
_this.setPrefix(data.prefix); }),
dataType: 'json'
});
}
function setPrefix(prefixData){
prefix = prefixData;
alret(prefix);
}
Upvotes: 0
Reputation: 15042
This is due to the asynchronous behaviour of your Ajax request. The getPrefix()
function will have returned before the Ajax request receives its response. You should pass the callback function to the getPrefix(country_id)
function, something like:
function getPrefix(country_id, callback) {
jQuery.ajax({
url: siteURL +"/wp-content/themes/storelocator/include/jquery.php",
data: {instance: 'getPrefix', country_id : country_id},
success: (function(data) {
callback.call(null, data.prefix);
}),
dataType: 'json'
});
}
And then call as follows:
function initForm() {
getPrefix(country_id, function (prefix) {
// 'prefix' is now available
});
}
Upvotes: 2
Reputation: 8819
The value of prefix is not being set because it is returned before the ajax post gets a response and the callback is triggered.
Instead, try
jQuery.ajax({
url: siteURL +"/wp-content/themes/storelocator/include/jquery.php",
data: {instance: 'getPrefix', country_id : country_id},
success: (function(data) {
prefix = data.prefix;
alert(prefix) // <--- This alerts correct value
return prefix;
}),
dataType: 'json'
});
}
Upvotes: 0