How to do autocomplete JqueryUi with PHP return multiple data?

Posted on

Coding Problem :

I have two inputs , I’m using automplete in only one. The autocomplete code:

$(document).ready(function() {
$.getJSON('include/funcoes/carrega_cidades.php', function(data){
var dados = [];

        $(data).each(function(key, value) {

        $('#cidade').autocomplete({ source: dados, minLength: 3});

cidade is the input that has autocomplete and is returning normally.
I need to bring in another input id_cidade , the city ID returned in autocomplete.


    $pdo = new PDO("mysql:host=localhost; dbname=iboard; charset=utf8;", "root", "");
$dados = $pdo->prepare("


echo json_encode($dados->fetchAll(PDO::FETCH_ASSOC));

How can I do this?


asked by anonymous 11.12.2015 / 20:32

Answer :

Answer 1 :

Simple, in jQuery UI, for you to have the value searched in the database being displayed in the list generated by autocomplete, you do not always have to use an array of string, but you can use an array of objects, since it has the attribute label as the desired value for display in the list generated by autocomplete.

For example:

 ['wallace', 'rray', 'bigown']

Can be used as:

[{label: 'wallace', id: 1}, {label: 'rray', id: 2}]

So you can access other attributes through ui.item .


$.getJSON('include/funcoes/carrega_cidades.php', function(data){

    var dados = [];

        $(data).each(function(key, value) {
            dados.push({label:, id:});

            source: dados,
            minLength: 3,
            select: function (event, ui) {
                  if (ui.item && {
                  return false;



Answer 2 :

  • Instead of taking the data just for the name of the city, place the object of the city in the vector.
  • Aim this vector as source of data
  • Include a method that will be called when choosing an item
  • Overload the autocomplete rendering function by telling it that you want to display the object’s field
  • It will look like this:

    $.getJSON('include/funcoes/carrega_cidades.php', function(data){
        var dados = data;
        $('#cidade').autocomplete({ source: dados, minLength: 3,
           select: function (event, ui) {
                if (ui.item &&{
                     return false;
        }).autocomplete( "instance" )._renderItem = function( ul, item ) {
          return $("<li>").append(;

    JQUERY UI Doc’s


    Answer 3 :

    Answer 4 :

    Answer 5 :

    Answer 6 :

    Answer 7 :

    Answer 8 :

    Answer 9 :

    Leave a Reply

    Your email address will not be published. Required fields are marked *