The title is a guess as to what is going wrong with my script:
This is in my global.js script:
alert(search.getLabelsNames(); //alerts as undefined.
$('#search').autocomplete({
source: function( request ) {
search.getLabelsNames();
},
minLength:1
});
This is in my functions.js script:
var search;
window.search = {
getLabelsNames:function( search ) {
$.ajax({
url : '../db_scripts/get_labels_names.php',
type: "POST",
data: { id: search }, //this defaults to nothing. not a problem
success : function( data ) {
var dataObj = jQuery.parseJSON( data );
$.each(dataObj, function() {
alert(this.name);
return this.name;
})
}
});
}
}
In the each function, this.name, returns every one of the label names correctly from the database. But when I call it from globals.js, it returns as undefined. If I return the number 1, the search.getLabelsNames() alerts 1.. so it has no problem finding the global function.
what is wrong with this script and why can’t global.js find the this.name that is being returned?
You have two problems:
You cannot return data from a
jQuery.eachcallback. The return value indicates whether to stop the iteration or not. From the documentation:You cannot return data from an Ajax callback. Ajax is asynchronous, which means in your case that
getLabelsNamesreturns before the response is retrieved and processed.Luckily, the autocomplete plugin accepts a function as source. You are already using it, but not correctly. Make it accept the second argument, which is a callback. From the documentation:
So what you have you have to do is passing this callback along to
getLabelsNamesso that it can be called in thesuccessmethod of the Ajax call:Note that I use
jQuery.map[docs] here, where returning a value form the callback has a different meaning. Don’t confuse it withjQuery.each.