I am attempting to be able to dynamically reload the variable I’m going to be using for an auto complete field, but I’m having trouble loading the initial call. Presently, my javascript consists of this:
<script type="text/javascript">
var myList;
function setTextSuggest() {
$("#loginInput").autocomplete({
source: myList,
appendTo: "#loginDiv"
});
};
$(document).ready(function() {
$.getJSON('StarWars.php', function(data) {
myList = JSON.parse(data);
//alert(myList); //DOES NOTHING WHEN UNCOMMENTED!!!!
setTextSuggest();
});
});
</script>
When I replace myList in the alert with ‘data[“info”]’, it spits out the JSON info I’m expecting. However, if I were to uncomment the alert and run it on myList, nothing at all would print. myList is supposed to have global scope here, but I can’t figure out why it’s not assigning inside my readied function.
Does anyone have any suggestions on how to resolve this issue?
EDIT:
The following is the object being returned from StarWars.php (created via json_encode):
{"UserList":["Han Solo","Leia Organa","Luke Skywalker","Darth Vader","Emperor Palpatine","Chewbacca","R2-D2","C-3PO","Lando Calrissian","Lobot","Yoda","Obi-Wan Kenobi","Uncle Owen","Aunt Beru","Wedge Antilles","Boba Fett"]}
If I set the getJSON request as:
$.getJSON('StarWars.php', function(data) {
myList = data.UserList;
alert(myList);
setTextSuggest();
});
Then it shows me the list of names, but I still have nothing set in my autocomplete.
Edit 2:
I have accepted Jack’s answer for this question. While my code does still have issues (autocomplete is not appending yet), Jack’s solution has moved it out of the realm of a question on global variables and JSON data retrieval and into a question about using the jQuery 1.8 autocomplete correctly. I feel this is a different question, so I’m marking this issue as complete. -D.G.
Judging from your question,
datais already a proper array / object (not text), so you don’t needJSON.parse()at all.Just this should do: