I fairly new to JQuery and perhaps trying to achieve something that might be abit harder for a beginner. However I am trying to create an autocomplete that sends the current value to a PHP script and then returns the necessary values.
Here is my Javascript code
$("#login_name").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://www.myhost.com/myscript.php",
dataType: "jsonp",
success: function(data) {
alert(data);
response($.map(data, function(item) {
return {
label: item.user_login_name,
value: item.user_id
}
}))
}
})
},
minLength: 2
});
And here is the the last half of "myscript.php"
while($row = $Database->fetch(MYSQLI_ASSOC))
{
foreach($row as $column=>$val)
{
$results[$i][$column] = $val;
}
$i++;
}
print json_encode($results);
Which produces the following output
[{"user_id":"2","user_login_name":"Name1"},{"user_id":"3","user_login_name":"Name2"},{"user_id":"4","user_login_name":"Name3"},{"user_id":"5","user_login_name":"Name4"},{"user_id":"6","user_login_name":"Name5"},{"user_id":"7","user_login_name":"Name6"}]
Can anyone tell me where I am going wrong please? Starting to get quite frustrated. The input box just turns "white" and no options are shown. The code does work if I specify an array of values.
UPDATE I have changed the code to and still having no luck.
$("#login_name").autocomplete({
source: "/ajax/login_name.php",
dataType: "json",
minLength: 2,
cache: false,
select: function(event, ui) {
alert(ui);
}
});
Using FireFox's Web Developer tool, I am getting an error "b is null".
some suggestions:
dataType= "jsop"
? It doesn't appear to be jsonp. I think you want "json".cache : false
in the options, as well. This insures the request is always made, and never satisfied from browser-side cache.alert()
there. Does it get invoked?alert()
to verify the value of the parameters.Simple Jquery ui autocomplete, for those who might need it.
your html form
Finally found the solution that fits my needs
A JSON strcuture is a flat string, while map expects an array or array like structure. try json decode on the string before using map.
I had a problem like you too. And now I fix it. The problem is my json that return from my server contain a syntax error.
In http://api.jquery.com/jQuery.getJSON/ tells that if there are some error in JSON, it will fail silently. The JSON must match the JSON standard here http://json.org/ .
For my error is my string in JSON is wrapping in only one quote. But the JSON standard accept only string that wrap in double quotes.
eg. "Hello World" not 'Hello World'
When you fix it you can set the source as string URL. The term will be in "term" query string. And it works!!
In case anyone else needs it :
The documentation for autocomplete in jQuery UI specifies the querystring parameter to use is 'term' and not 'q'... or least it does now.