Javascript Array created from Ajax Request
I am trying to populate an array (for use with jquery-ui element) using an Ajax request which I am not very familiar with. There are two files, selectStudents.php which is what will be viewed and loadStudents.php which is what the Ajax requests.
When I view loadStudents.php, copy the output, and replace the Ajax request开发者_StackOverflow with that instead it works perfect, so I am simply doing something wrong with my ajax. Anyone see off hand what it is?
<script>
$(function() {
var availableTags = new Array();
new Ajax.Request('includes/loadStudents.php', {
onSuccess : function(xmlHTTP){
eval(mlHTTP.responseText);
}
});
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
Thanks!
That looks like prototype. If you're using jQuery, an ajax request looks like this:
$.ajax('includes/loadStudents.php', {
success: function(data) {
// no need to eval, jQuery handles parsing the json for you
console.debug(data);
}
});
See jQuery.ajax
for more details.
Additionally using jQuery UI you can let autocomplete handle the ajax for you:
$('#tags').autocomplete({
source: 'includes/loadStudents.php'
});
See jQuery UI Autocomplete for further usage.
Assuming Ajax.Request
works, the reason why the array is not set correctly is described in my comment: Ajax is asynchronous. The .autocomplete
call is executed before the onSuccess
callback is run (hence before the array elements are set).
You could solve this by simply putting the .autocomplete()
call inside the function. But it would be much better to solve the problem in a different way:
Don't return JavaScript in your PHP script. Return JSON:
<?php
$data = array('Doe, Kid', 'Smith, John');
echo json_encode($data);
?>
Then your JavaScript would look like:
$(function() {
$.getJSON('includes/loadStudents.php', function(data)
$( "#tags" ).autocomplete({
source: data
});
});
});
Or as @scurker already mentioned, set the URL as value to source
. It is described in the documentation:
Autocomplete can be customized to work with various data sources, by just specifying the source option. A data source can be:
- an Array with local data
- a String, specifying a URL
- a Callback
(...)
When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The request parameter "term" gets added to that URL. The data itself can be in the same format as the local data described above.
So on order for this to work, you have to return JSON, as shown above.
精彩评论