I need to attach results from a jQuery function.
When the user types in the search field, a function is called and data is returned from my database.
I can see the returned data using alert function
<input type="text" name="symbol" id="symbol" required="required" onkeyup="findmatch();">
The jQuery function called is below
function findmatch() {
var symbol= document.getElementById("symbol").value;
$.post("portfolio/searchStock.php",
{
search:symbol
},
function(data,status) {
alert(data);
});
}
I need the data returned to be attached as an autocomplete, I have tried using the following within the function.
I don't understand why it doesn't work
$( "#symbol" ).autocomplete({
source: data
});
The php file echoes data as below
if (isset ($_POST['search'])){
$search = $_POST['search'];
if(!empty ($search)){
$query="select * from companylist where symbol like '".mysql_real_escape_string($search)."%'";
$query_run = mysql_query($query);
while ($query_row = mysql_fetch_assoc($query_run)){
$symbol = $query_row['symbol'];
echo $symbol;
}
}
}
You need to format the output of the db call:
while ($query_row = mysql_fetch_assoc($query_run)){
$symbol[] = $query_row['symbol'];
}
echo json_encode($symbol);
Then, you need to parse the returned data.
var sourceData = [];
var arrData = $.parseJSON(data);
foreach(x in arrData)
{
sourceData.push(arrData[x]);
}
$( "#symbol" ).autocomplete({
source: sourceData
});