Viewed   134 times

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?



You can stick very much to the remote demo of jQuery UI's Autocomplete:

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 ) {
        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

Friday, August 12, 2022

You need to transform the object you are getting back into an array in the format that jQueryUI expects.

You can use $.map to transform the dealers object into that array.

    source: function (request, response) {
        $.getJSON("/example/location/example.json?term=" + request.term, function (data) {
            response($.map(data.dealers, function (value, key) {
                return {
                    label: value,
                    value: key
    minLength: 2,
    delay: 100

Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label and value properties that $.map's callback function return.

Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:

  • Is an array of objects that have a label property, a value property, or both, or
  • Is a simple array of strings

In other words, if you can format the data like this:

[{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]

or this:

["dealer 5", "dealer 6"]

Then your JavaScript becomes much simpler:

    source: "/example/location/example.json"
Thursday, October 13, 2022

here is a simple one

here is my test.php for testing only


// this is just a test
//send back to the ajax request the request

echo json_encode($_POST);

here is my index.html

<!DOCTYPE html>



<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">

<script src=""></script>
        // click on button submit
        $("#submit").on('click', function(){
            // send ajax
                url: 'test.php', // url where to submit the request
                type : "POST", // type of action POST || GET
                dataType : 'json', // data type
                data : $("#form").serialize(), // post data || get data
                success : function(result) {
                    // you can see the result from the console
                    // tab of the developer tools
                error: function(xhr, resp, text) {
                    console.log(xhr, resp, text);


Both file are place in the same directory

Saturday, December 17, 2022

It's not much different.

$idcateg = trim($this->input->post('idcategory'));
$result = array();
$id = mysql_real_escape_string($idcateg);
$res = mysql_query("SELECT * FROM subcategories WHERE category = $id");
while ($row = mysql_fetch_array($res)) {
  $result[] = array(
    'id' => $row['subcatid'],
    'desc' => $row['description'],
echo json_encode($result);


$.post("<?=base_url()?>index.php/rubro/list_ajax/", { 
  'idcategory' : idc },
  function(data) {
    var sel = $("#select");
    for (var i=0; i<data.length; i++) {
      sel.append('<option value="' + data[i].id + '">' + data[i].desc + '</option>');
  }, "json");
Monday, August 29, 2022

You need to change your source to meet the following specifications (outlined in the documentation for the widget). The source must be an array containing (or return an array containing):

  • Simple strings, or:
  • objects containing a label property, a value property, or both.

If for some reason you cannot change what your remote source is returning, you can transform the data once it has successfully retrieved. Here's how you would do that:

    source: function (request, response) {
            url: "http://mysite.local/services/suggest.ashx",
            data: { query: request.term },
            success: function (data) {
                var transformed = $.map(data, function (el) {
                    return {
                        label: el.phrase,
            error: function () {

As you can see, you'll need to make the AJAX call yourself by passing in a function to the source option of the widget.

The idea is to use $.map to transform your array into an array that contains elements that the autocomplete widget can parse.

Also notice that the data parameter passed to the AJAX call should end up as ?query=<term> when the user types a term.

Saturday, September 24, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :