My function is very simple, and based on what I found here. Yet I cant seem to make it work, whats wrong?
function ajax(url) {
var result;
$.ajax({
url: url,
success: function(data) {
result = data;
//$('#test').html(data);
}
});
return result;
}
The function is getting the data, for if I uncomment the commented code and call it, then the data is shown inside the #test element. However, if I write
var test = ajax('my-url.php');
$('#test').html(test);
then it doesnt work. My guess is that for some reason, the data in “data” is not being stored in the variable “result”. But I cant figure out why, nor how to solve it. Any help is appreciated.
The
resultvariable is not being changed until the AJAX call finishes, by which point theajaxfunction has already returned. This is the entire point of callbacks, the ability to schedule a task to be executed when an event is finished.Javascript (in-browser) is inherently asynchronous.
Alternatively, you can pass in
async: falseto your$.ajaxcall and it will wait until it’s finished, but reverting back to your original style makes more sense.Edit: It looks like what you’re doing can be accomplished with
$.load().