Author Topic: Autocomplete using array of objects  (Read 5402 times)

nuno.nogueira

  • Pro Economy
  • Jr. Member
  • *
  • Posts: 95
    • View Profile
Autocomplete using array of objects
« on: February 05, 2014, 09:38:49 pm »
I have a MySQL table like:

Code: [Select]
name   | id
John   | 1
Mike   | 2
Kelly  | 3
In Jquery, I'm able to use autocomplete showing "name" in the pop-up list while inserting the "id" in the input:

Code: [Select]
var names=[
    {label:"John", value:1},
    {label:"Mike", value:2},
    {label:"Kelly", value:3}
];
$('#myDiv').autocomplete({
    source: names
})
This is working fine, but now I need to reproduce the array of objects "names" using PHP. I'm trying the following in PHP:

Code: [Select]
$sql ="SELECT id, nome FROM table";
    $result = $pdo->query($sql);
    $rows = $result->fetchAll(PDO::FETCH_ASSOC);

    $output=array();;

    foreach($rows as $key){
        array_push($output, array($key{"nome"}=>intval($key{"id"})));
    };

    echo json_encode($output);
This is returning:

Code: [Select]
[{"John":1},{"Mike":2},{"Kelly":3}]In Jquery, I'm now using Ajax to call myscript.php:

Code: [Select]
var names= [];
    $.ajax({
        url: "../myscript.php",
        success: function (response) {
            names = response.split(",");
        }
    });
But this is just displaying the same result in the cell:

Code: [Select]
[{"John":1},{"Mike":2},{"Kelly":3}]So, I guess the soulution is to add label and value to each of the objects in PHP, or what can solve the problem?

Thanks in advance for any help!

paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6310
    • View Profile
Re: Autocomplete using array of objects
« Reply #1 on: February 05, 2014, 10:16:30 pm »
Yes it has be in the 2nd format below :

There are two supported formats:

An array of strings: [ "Choice1", "Choice2" ]

An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

nuno.nogueira

  • Pro Economy
  • Jr. Member
  • *
  • Posts: 95
    • View Profile
Re: Autocomplete using array of objects
« Reply #2 on: February 05, 2014, 11:36:41 pm »
yeah, I already know that, but it just doesn't work...