If you look at the function below, on line 11 where it alert(template);
. It prints undefined
. If I alert(template);
inside the ajax succes
The success
function is a callback. The javascript engine makes the request to the server, and when the server responds to the data, then it runs the success
function and you have the data, so the success
function is run after your if statement at the end, even though its defined beforehand.
Javascript code is run inside of an Event Loop, all $.ajax
is doing is starting an asynchronous event and specifying what to do when that event occurs.
template isnt defined until your ajax request is completed.
thats why it shows fine in the success function.
not sure what framework that is ( JQuery I presume ) but you need to do the callback in the ajax success function.
No, it's not a scope issue, it's a timing issue.
The AJAX call is asynchronous, so the success callback runs later, when the response arrives. The variable is simply not set yet, when you try to use it.
You can't return the value from the function, as the success callback never runs until you have exited the function. Always use the callback that is sent to the function:
function load_template(path, data, callback){
$.ajax({
url: path,
success: function(uncompiled_template){
var template = Handlebars.compile(uncompiled_template);
callback(template, data);
}
});
}
ajax is asynchronous. to explain in simple terms: ajax works like it runs on a separate "thread", processing in the background while your code continues.
by the time you called load_template()
, it alerts after $.ajax()
was called but before the template was returned thus undefined
.
what you can do is this so everything runs after a success has been returned:
function load_template(path, data, callback){
$.ajax({
url: path,
success: function(uncompiled_template){
var template = Handlebars.compile(uncompiled_template);
alert(template);
if(callback){
callback(template, data);
}else{
return template(data);
}
}
});
}