3

I need to convert a php object array into a javascript variable inorder for it to be used in 'easyautocomplete' plugin. Here is a rundown of what I'm trying to achieve:

var_dump of PHP object returned from database:

array(223) {
  [0]=>
  object(stdClass)#5 (9) {
    ["id"]=>
    string(2) "10"
    ["no"]=>
    string(3) "CN1"
    ["name"]=>
    string(10) "Cyclops"
  }
  [1]=>
  object(stdClass)#6 (9) {
    ["id"]=>
    string(2) "11"
    ["no"]=>
    string(3) "CN2"
    ["name"]=>
    string(11) "Professor X"
  }
  ..
  ..

Required javascript format:

var characters = {

    data: [
        {"name": "Cyclops", "id": 1},
        {"name": "Professor X", "id": 2}
        ],

    getValue: "name",

    list: {

        onSelectItemEvent: function() {

            var value = $("#character1").getSelectedItemData().id;

            $("#character").val(value).trigger("change");
        }
    }
};

What I tried:

var characters = <?php echo json_encode(['data' => $chars]); ?>;

Result:

var characters = {

    "data": [
    {"id":"10","no":"CN1","name":"Cyclops"},
    {"id":"11","no":"CN2","name":"Professor X"}

]};

It seems I have almost got the result I need, but I don't know how I'll append the remaining properties starting from getValue : "name" list: { ..... to the character variable.

Also, it seems the resulting variable has double quotes around the "data" attribute but I'm not sure if that'd cause a problem.

Link to the example I'm trying to implement: Link

Inception
  • 455
  • 1
  • 9
  • 32
  • try `characters = JSON.parse('= json_encode(["data" => $chars]); ?>');` – xanadev Jun 17 '18 at 10:22
  • Is JSON.parse actually required? Also how do I then append the remaining parts to the `characters` variable? – Inception Jun 17 '18 at 10:31
  • There's no need to append your values. Your can leave them as is and only provide data array. – u_mulder Jun 17 '18 at 10:37
  • @u_mulder But I need to append the part starting from `getValue: "name"...` to the variable for the plugin to properly work! – Inception Jun 17 '18 at 10:38
  • Json data can't be used inside JS unless you parse it using JSON.parse(), if you need to append json data to your characters object then just append a data property with a value set to `data: JSON.parse('= json_encode($chars); ?>');` – xanadev Jun 17 '18 at 10:49

1 Answers1

0

Client-side behaviour should be on client side, there's no need to append anything to data, just provide required dataset, all other fields can be defined in js:

var characters = {
    data: <?=json_encode($chars)?>,
    getValue: "name",
    list: {
        onSelectItemEvent: function() {
            var value = $("#character1").getSelectedItemData().id;
            $("#character").val(value).trigger("change");
        }
    }
};
u_mulder
  • 54,101
  • 5
  • 48
  • 64