0

I have a MySQL table like:

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:

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:

$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:

[{"John":1},{"Mike":2},{"Kelly":3}]

In Jquery, I'm now using Ajax to call myscript.php:

var names= [];
    $.ajax({
        url: "../myscript.php",
        success: function (response) {
            names = response.split(",");
        }
    });

But this is just displaying the same result in the cell:

[{"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!

3
  • 1
    Pretty sure you just need to add the 'label' and 'value' to the objects in PHP, and that should return your properly formatted values. Commented Feb 5, 2014 at 16:15
  • 1
    Additionally, for easier handling of the json content-type use $.getJSON instead of $.ajax. see api.jquery.com/jquery.getjson Commented Feb 5, 2014 at 16:19
  • @Mordred I'm trying just that but it isn't working, would you paste an example code to replace: array_push($output, array($key{"nome"}=>intval($key{"id"}))); Commented Feb 5, 2014 at 16:27

1 Answer 1

0

You need to use the PHP header() method to do:

header('CONTENT-TYPE: application/json');
echo json_encode($output);

might want to reference documentation in case I have a typo there :)

But in any case, once the return type of the JSON is the right content-type, JQuery will automatically convert that response into an array of objects.

[edit] Addendum...to the second part of your question:

For auto-complete to work it depends on your IDE...and your IDE depends on an object definition within the same language that you are using. I use phpStorm. So, if I wanted to make auto-complete work in phpStorm for the JavaScript AJAX return, I would have to create a dummy JavaScript object (this can be anywhere in your code, even an un-used JS file that is there solely to define dummy objects...just has to have a unique name parseable by your IDE):

//dummy object used for auto-completion to work
function NameObject(param, param2) {
    this.label = param;
    this.value = param2;
}

Then, on my AJAX return, I would have to put:

success: function(response) {
    /** @var NameObject[] response */
}

I dont' know of any other way to do this, and how well that would work depends on the IDE. I've never done this for JavaScript as it seems to be more work than it's worth.

[edit2] Addendum on formatting PHP to output objects with named keys Okay, maybe I misunderstood...didn't notice at first that your labels weren't in the JSON you were outputting....so in your PHP, if you want the .label and .value to work, your PHP needs to generate it like so:

$results = array();
foreach($rows as $key){
    $obj        = new stdClass();
    $obj->label = $key['nome'];
    $obj->value = intval($key['id']);
    $results[]  = $obj;
};
echo( json_encode($results) );

OR

$results = array();
foreach($rows as $key){
    $arr          = array();
    $arr['label'] = $key['nome'];
    $arr['value'] = intval($key['id']);
    $results[]    = $arr;
};
echo( json_encode($results) );
Sign up to request clarification or add additional context in comments.

12 Comments

That is returning: <b>Warning</b>: Cannot modify header information - headers already sent by (output started at...) together with the same result above.
Then you are echo-ing something prior to your echo code that is preventing the headers from being sent, just as it said. This could be that you are actually echo-ing something out in your code, or it could be a simple mistake such as having a space or return after a ?> in a file somewhere, which is why PHP recommends never closing a file with ?>
and note the third paragraph here about omitting the php closing tag: php.net/manual/en/language.basic-syntax.phptags.php
I can't see the code for your popup, but if you are still seeing the JSON as a string, then back to the header() needing to send application/json. If it sends application/json, jQuery should be parsing that and you should be able to do: response[0].label in your success method.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.