1

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

1
  • 1
    alert("<?php echo $shipping_part_list_array; ?>"); Change to alert("<?php echo addslashes ($shipping_part_list_array); ?>"); or see on raw html code Commented Aug 29, 2012 at 9:05

2 Answers 2

3

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

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

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; ?>;
4
  • function Array() { [native code] } i get this when i alert without "". Commented Aug 29, 2012 at 9:08
  • @Toma right, that's what I warned about in my answer, if you want to debug the object itself, you should use console.log() Commented Aug 29, 2012 at 9:09
  • with console.log() and simple quotes i get Array. In my error_log i gave out the $db_obj->getArticleList($elements) the array is filled with data. Commented Aug 29, 2012 at 9:13
  • @Toma I've updated my answer, please check. Btw, I never said to put single quotes around the value. Commented Aug 29, 2012 at 9:15

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.