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!

  • 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. – Mordred Feb 05 '14 at 16:15
  • 1
    Additionally, for easier handling of the json content-type use $.getJSON instead of $.ajax. see http://api.jquery.com/jquery.getjson/ – Jojo Feb 05 '14 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"}))); –  Feb 05 '14 at 16:27

1 Answers1

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) );
Kevin Nelson
  • 7,613
  • 4
  • 31
  • 42
  • That is returning: Warning: Cannot modify header information - headers already sent by (output started at...) together with the same result above. –  Feb 05 '14 at 16:19
  • 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 ?> – Kevin Nelson Feb 05 '14 at 16:21
  • http://stackoverflow.com/questions/1793482/php-error-cannot-modify-header-information-headers-already-sent – Kevin Nelson Feb 05 '14 at 16:23
  • 1
    and note the third paragraph here about omitting the php closing tag: http://www.php.net/manual/en/language.basic-syntax.phptags.php – Kevin Nelson Feb 05 '14 at 16:26
  • I've deleted ?> from the database connection file and the warning was gone. But autocomplete is now an empty pop-up. Looking at "Network" in dev tools I can see the result is the same as in my question. –  Feb 05 '14 at 16:26
  • I've added an addendum about auto-completion – Kevin Nelson Feb 05 '14 at 16:32
  • I'm using Aptana. As I mentioned in my question, if the array of objects is created locally (ie in Jquery) it runs well. The problem is generating it in PHP. –  Feb 05 '14 at 16:43
  • If Aptana understands PhpDoc blocks or a similar concept for JavaScript, you use that to define what type of object is returned. The problem is (at least with phpStorm) it's not going to read PHP objects for JavaScript...so you have to create the dummy object in JS and use the phpDoc block (or similar) to define that the return is a return of the dummy type. – Kevin Nelson Feb 05 '14 at 16:46
  • 2nd addendum added...with that, all 3 questions...how to get it as JSON, how to get intellisense to work from AJAX response, and how to format PHP to be the type of object needed for that intellisense. – Kevin Nelson Feb 05 '14 at 16:59
  • Thanks, that's more what I meant! Both of your solutions produce the same output: [{"label":"John","value":1}, ...]. Apart from the commas around label and value, this is what I want, but the pop-up display is showing: [{"label":"John","value":1}, ...] instead of John –  Feb 05 '14 at 17:08
  • 1
    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. – Kevin Nelson Feb 05 '14 at 22:09
  • Both of my solutions were supposed to return the same output...I was giving two methods to do the same thing based on whether you want to use an object or an array. – Kevin Nelson Feb 05 '14 at 22:09