Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery UI autocomplete with json and ajax

I've seen a lot of questions dealing with passing an array with label and value properties via JSON, but not much about passing strings. My problem is that I cannot seem to get my autocomplete to fill. I ran a dump function and am getting these sample values passed via JSON to the autocomplete:

0: 23456
1: 21111
2: 25698

Here's some code:

$("#auto_id").autocomplete( {
    source: function(request,response) {

        $.ajax ( {
          url: "fill_id.php",
          data: {term: request.term},
          dataType: "json",
          success: function(data) {
            //what goes here?
                 } 
    }) }
   });

Here is fill_id.php:

$param = $_GET['term'];
$options = array();


$db = new SQLite3('database/main.db');
    $results = $db->query("SELECT distinct(turninId) FROM main WHERE turninid LIKE '".$param."%'");


while ($row_id = $results->fetchArray()) {
        $options[] =  $row_id['turninId']; 
    }   
echo json_encode($options);

My autocomplete remains blank. How do I change my JSON array to fill it? Or what do I include in my ajax success function?

like image 351
hereiam Avatar asked Aug 07 '12 18:08

hereiam


People also ask

How hard is it to get jQuery Ajax autocomplete?

I hope this jQuery, AJAX, PHP, and JSON autocomplete example has been helpful. As you've seen, once you know the syntax to use on the client and server, getting jQuery AJAX autocomplete code isn't too hard at all.

How do I add autocomplete to a list in jQuery?

jQuery UI autocomplete with PHP and AJAX. The autocomplete functionality shows the suggestion list according to the entered value. The user can select a value from the list. With jQuery UI you can easily add autocomplete widget to the input element. Navigate to the suggestion list either by mouse or keyboard arrow keys.

How to add autocomplete to a PHP script?

To keep it simple, I recommend creating a directory named autocomplete under a PHP web server (like Apache) that you have access to, then placing this file in that directory. In just a few moments you can put the corresponding PHP script in that same directory.

What is autocomplete and how does it work?

Autocomplete. Enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.


1 Answers

You can stick very much to the remote demo of jQuery UI's Autocomplete: http://jqueryui.com/resources/demos/autocomplete/remote-jsonp.html

To get your results into the autocompleted list, you need to put a object with a label and a value to the response parameter (which is actually a function) inside your ajax success function:

source: function( request, response ) {
    $.ajax({
        url: "fill_id.php",
        data: {term: request.term},
        dataType: "json",
        success: function( data ) {
            response( $.map( data.myData, function( item ) {
                return {
                    label: item.title,
                    value: item.turninId
                }
            }));
        }
    });
}

But this will only work if you modify yor fill_id.php a bit:

// escape your parameters to prevent sql injection
$param   = mysql_real_escape_string($_GET['term']);
$options = array();

// fetch a title for a better user experience maybe..
$db = new SQLite3('database/main.db');
    $results = $db->query("SELECT distinct(turninId), title FROM main WHERE turninid LIKE '".$param."%'");

while ($row_id = $results->fetchArray()) {
    // more structure in data allows an easier processing
    $options['myData'][] = array(
        'turninId' => $row_id['turninId'],
        'title'    => $row_id['title']
    ); 
}

// modify your http header to json, to help browsers to naturally handle your response with
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

echo json_encode($options);

Of course, when you don't have a title or anything in your table, you can also just leave your response as it is and repeat the id in your success callback. Important is, that you fill your response function in the autocomplete with a value/item pair:

// this will probably work without modifying your php file at all:
response( $.map( data, function( item ) {
    return {
        label: item,
        value: item
    }
}));

edit: updated the reference link to the new jquery UI's autocomplete ui

like image 99
con Avatar answered Sep 25 '22 20:09

con