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?
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 thegetPrefix(country_id)function, something like:And then call as follows: