All,
I’ve got the following code to which is basically a function that loads some search terms in it when the DOM is loading:
window.myAutocompleteFunction = function(){
return ['Test Saying','sit amet consectetur adipiscing','elit Nulla et justo'];
};
This works fine for my live search and updates correctly. I’m trying to populate these values based on some information from my database though. I tried to update my code to use a .get function to populate my return values and I tried to make it look like this:
window.myAutocompleteFunction = function(){
$.get('http://localhost/website/load_users.php', function(data) {
alert(data);
return [data];
});
};
It tries to load the users and in my alert it is the same as when it’s manually typed in but for some reason when I do the search it doesn’t work. Any idea how to get the same results from my file and have the search work the same?
EDIT: The only thing in my load_users.php file right now is the following:
'Test Saying','sit amet consectetur adipiscing','elit Nulla et justo'
I’m going to try and populate that with database values but just trying to get this to work for now.
Another Edit: I also tried to make my code like the following just to see if it work work:
window.myAutocompleteFunction = function(){
jQuery.get('http://localhost/okyne/load_users.php', function(data) {
alert(data);
return ['Test Saying','sit amet consectetur adipiscing','elit Nulla et justo'];
});
};
This doesn’t work either so I’m not sure why it wouldn’t work and the only thing that works for me so far is the first code snippet that I provided.
Any help you can provide is greatly appreciated!
Your
$.getcan’t return a value like that, because it runs asynchronously and the browser starts evaluating it, moves on and finishes with that fn. before it completes. Also, that particularreturnwill target the inner success-callback function, not the autocomplete function. You will have to load the data and create that function in the success callback.Here is a mockup example. http://jsfiddle.net/Nf2UD/
Note I used setTimeout to make sure the ajax call was finished, but you will want to ensure you call randomFn during your page initialization, to ensure it has run before you try and use autocomplete. You can check this in a couple ways — having a global variable to track the status, checking if the autocomplete function is undefined, …. In truth this isn’t really the point of asynchronous methods, but whatever works for you I guess.