Geoffrey
Geoffrey

Reputation: 467

jQuery Autocomplete using json data

I have been banging my head against the wall for hours on this, and I can't seem to figure it out. I have a php file that gets data from a table and converts it into json and displays it like so:

{"id":1,"name":"GR Gas","number":"1","gas":"0.02500000","diesel":"0.03500000"}

I have the jQuery UI Autocomplete plugin on another php web page that has this jQuery written:

        $(function () {

            $("#customers").autocomplete({
                source: "../assets/json_clients.php",
                dataType: 'json',
                minLength: 2,
                select: function (event, ui) {
                    $("customer-id").val(ui.item.number);
                }
            });
        });

So far it does it's job, it reads the json, and creates the autocomplete drop down under the textbox and i can click on the item. However it is displaying everything in that dropdown that the json outputs, for example it has GR Gas, 1, etc. I only want it do display the "name". When it is clicked it sets the values of hidden text boxes, can someone point me in the right direction?

Thank you in advance for your help!

EDIT Here is the PHP that creates the json:

<?php

header('Content-Type: application/json');
require 'class_dbconnection.php';

$sql = 'SELECT id,c_name,c_number,price_gas,price_distillate FROM mb_clients';

foreach ($Conn->query($sql) as $row) {
    $result = array('id' => $row['id'], 'name' => $row['c_name'], 'number' => $row['c_number'], 'gas' => $row['price_gas'], 'diesel' => $row['price_distillate']);
    echo json_encode($result, JSON_FORCE_OBJECT);
}

Upvotes: 0

Views: 6496

Answers (1)

Martina
Martina

Reputation: 769

You can use the 'source' option as a function, do your ajax there and manipulate the data returned, read the 3 options for source, you need to return string, array in expected format or use it as function:

http://api.jqueryui.com/autocomplete/#option-source

It may also work if you add 'label' to your JSON, but then you don't have space to manipulate anything else.

Here is an example of using it as function:

source: function(request, response)
{
  var searchTerm = request.term; // This will be the search term

$.ajax({ 
    url: url,
    data: request, // if request does not work with your php, try request.term
    success: function(json)
    {

        var arr = [ { label: "Choice1", value: "value1" }, ... ]
        response(arr); 
    },
    error:function(errObj)
    {
        var arr = []; 
        response(arr);
    }
    });
},

Also have a look at: http://api.jqueryui.com/autocomplete/#event-response

You don't even need to use 'source' it seems.

Upvotes: 1

Related Questions