Barta Tamás
Barta Tamás

Reputation: 899

json_encode pass php array to javascript array

I have a more dimensional php array that i want to pass to a javascript array.

This is the array:

$this->_db_list_arrray[$this->getID()][$key] = $row;

its like "16":[[{"article_no_internal":"9987213"}]] and so on. I encode it like this:

$shipping_part_list_array = json_encode($db_obj->getArticleList($elements));

and in javascript

alert("<?php  echo $shipping_part_list_array; ?>");

but the alert only shows [].

Is there a better way to pass php array to java script array?

array(1) {
  [16]=>
  array(2) {
    [0]=>
    array(1) {
      [0]=>
      array(2) {
        ["article_no_internal"]=>
        string(6) "999184"
        ["article_name_internal"]=>
        string(29) "Geschenkbox Kerzenschein 2011"
      }
    }
    [1]=>
    array(1) {
      [0]=>
      array(2) {
        ["article_no_internal"]=>
        string(6) "999184"
        ["article_name_internal"]=>
        string(29) "Geschenkbox Kerzenschein 2011"
      }
    }
  }
}

this is in my console, now i need to parse to get the right data. Thank you

Upvotes: 1

Views: 2598

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173562

You should not put double quotes around the JSON encoded value; just the following will do:

alert(<?php echo $shipping_part_list_array; ?>);

Though, for debugging purposes the following would be better:

console.log(<?php echo $shipping_part_list_array; ?>);

Lastly, to assign it to a JavaScript variable:

var list = <?php echo $shipping_part_list_array; ?>;

Upvotes: 2

Mihai Iorga
Mihai Iorga

Reputation: 39704

You need to add single quotes to alert your JSON string:

alert('<?php  echo $shipping_part_list_array; ?>');

Upvotes: 3

Related Questions