I'm trying to set up an autocomplete that's getting its data from a csv. The csv has a list of restaurant names and food types. I've gone over some of the other posts here at SO, and the autocomplete documentation, but I think it's the two fields in the csv, rather than one field that is tripping me up.
Example csv data:
McDonald's,Fast Food
Olive Garden,Italian
Manny's,Steakhouse
Carino's,Italian
etc...
The user should be able to search by either food type or restaurant name:
<body>
<br>
<br>
<label id="lblSearchRestaurant" for="txtSearchRestaurant">Search for a Restaurant</label>
<input type="text" id="txtSearchRestaurant">
</body>
Here's what I've tried for the autocomplete setup:
$(function() {
$( "#txtSearchRestaurant" ).autocomplete({
source:searchRestaurant.php,
select: function( event, ui ) {
$( "#search" ).val( ui.item.label + " / " + ui.item.actor );
return false;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.data( "item.autocomplete", item )
.append( "<a><strong>" + item.label + "</strong> / " + item.actor + "</a>" )
.appendTo( ul );
};
});
I need to serve the data using a PHP script. Here's what I have at this point:
<?php
$header = NULL;
$restaurants = array();
if (($file = fopen('restaurants.csv', 'r')) !== FALSE) {
while (($row = fgetcsv($file, 1000, ',')) !== FALSE) {
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($file);
}
$term = $_GET['term'];
foreach($restaurants as $k=>$v) {
if(preg_match("/^$term/i", $v)) { $return[] = $v; }
}
foreach($restaurants as $k => $v) {
if(preg_match("/$term/i", $v)) { $return[] = $v; }
}
echo json_encode(array_values(array_unique($return)));
None of the above has worked, so I tried formating the restaurant data in to an array, rather than just comma-separated values:
[
{name:"McDonald's",type:"Fast Food"},
{name:"Olive Garden",type:"Italian"},
{name:"Manny's",type:"Steakhouse"},
{name:"Carino's",type:"Italian"}
];
I tried that locally in the <script>
tag and in a separate file, but neither worked.
So, none of the above worked for me, but I'm not the best at arrays yet and for that matter, using JSON data, so I probably don't have the php script set up properly.
I'd appreciate it if someone could point me in the right direction here.
Thanks.
Note to potential answers: The jquery UI autocomplete, the format of the incoming data (as described above) and using PHP to get the data from the csv to the autocomplete are all requirements for this. Those three stipulations are, unfortunately, not under my control.