1

PHP:

json_encode($data)

outputs

[{"sid":"0032","name":"Germany"}]

I want to consume this in jquery-ui autocomplete. But in jquery-ui doc the source looks like this

    var projects = [
        {
            value: "jquery",
            label: "jQuery",
            desc: "the write less, do more, JavaScript library",
            icon: "jquery_32x32.png"
        }
    ];

How can I convert the php output to such an array in javascript?

reference: http://jqueryui.com/demos/autocomplete/#custom-data

0

3 Answers 3

2

remake the array:

$toJSON = array();
foreach($data as $num => $val){
    $toJSON[$num]['value'] = $val['sid'];
    $toJSON[$num]['label'] = $val['name'];
}
echo json_encode($toJSON);
Sign up to request clarification or add additional context in comments.

Comments

1
var availableTags = <?=json_encode($yourArray);?>;

$( "#yourInput_text" ).autocomplete({
    source: availableTags,
    focus: function (event, ui) {
        $("#yourInput_text").val(ui.item.name);
        return false;                                               },
    select: function (event, ui) {
        $("#yourInput_text").val(ui.item.name);
        $("#yourInput).val(ui.item.sid);                                                                
        return false;                                               },
minLength: 4                                                            
});

Comments

0

What about:

var projects = eval(data);

in your javascript code.

1 Comment

there is no need to use eval there, with php you can put the json encoded array wherever you want

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.