Reputation: 1384
JQuery UI auto-complete passed with local array is showing filtered result.
This is the code:
var localArray = ["BASIC","C++","Fortran","Haskell","JavaScript","PHP","Scheme"];
$( "#tags" ).autocomplete({
source: localArray
});
But when I passed php file to source tag (which is returning the same array), now auto-complete is showing (whole data) unfiltered result whichever character is pressed (matched or unmatched).
This is the code:
$( "#tags" ).autocomplete({
source: "PHP_Code/MyAjax.php?page=tut_search_ac"
});
Here is PHP File:
$query = "SELECT title FROM tutorial";
$rs = mysql_query($query) or die(mysql_error()." in query $query");
if($rs)
{
while($row = mysql_fetch_array($rs))
{
$contents[] = $row['title'];
}
}
echo json_encode($contents);
It always show all the values of array. You can also check it HERE.
Please give me some solution.
Thank you in advance.
Upvotes: 0
Views: 161
Reputation: 1384
I realized the issue. There was nothing actual wrong in the above code but a little lack of concept.
JQuery only filter the array given by JavaScript locally.
But does not filter the response text returned by php/server-side.
Therefore we have to include filtering code in php file. (which is also ideal)
$keyward = $_REQUEST['term']; //term is equal to keyword
$query = "SELECT title FROM tutorial WHERE title LIKE '%$keyward%' ORDER BY title";
$rs = mysql_query($query) or die(mysql_error()." in query $query");
if($rs)
{
while($row = mysql_fetch_array($rs))
{
$contents[] = $row['title'];
}
}
echo json_encode($contents);
Please feedback in comments if you consider something wrong.
Upvotes: 1
Reputation: 13630
Using the source
property as a remote resource rather than local requires your data to be in a specific format. Specifically, each item is a JSON object with both label
and value
properties. Change your PHP script to output your JSON data like this:
[
{ label: "BASIC", value: "BASIC" },
{ label: "C++", value: "C++" },
{ label: "Fortran", value: "Fortran" },
{ label: "Haskell", value: "Haskell" },
{ label: "JavaScript", value: "JavaScript" },
{ label: "PHP", value: "PHP" },
{ label: "Scheme", value: "Scheme" }
]
To get this structure from your PHP, you need a PHP array with this format:
$contents[] = array( "label" => "BASIC", "value" => "BASIC" );
$contents[] = array( "label" => "C++", "value" => "C++" );
$contents[] = array( "label" => "Fortran", "value" => "Fortran" );
$contents[] = array( "label" => "Haskell", "value" => "Haskell" );
$contents[] = array( "label" => "JavaScript", "value" => "JavaScript" );
$contents[] = array( "label" => "PHP", "value" => "PHP" );
$contents[] = array( "label" => "Scheme", "value" => "Scheme" );
echo json_encode($contents);
You can also look here to see how to manipulate jquery ui to fit your data:
https://jqueryui.com/autocomplete/#custom-data
Upvotes: 1