0

I have a php array of products that I want to move to javascript but when I json_encode it errors out giving me

Uncaught SyntaxError: Unexpected token ;

The debugger is giving me

var phpPro=;

and the code reads

var phpPro=<?php echo json_encode($pro)?>;

I have also encoded the array in the php script and tried to assign to js variable from there.

php =

$jpro=json_encode($pro);

js =

var phpPro=<?php echo $jpro;?>;

This code was actually working and now that I'm trying to copy it to another site it is not working. All the products are in the php recordset when displayed so I know they are there.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Looked at escaping options on the encode, or checked [json_last_error](https://www.php.net/manual/en/function.json-last-error.php)? – ficuscr Jun 04 '19 at 20:10
  • `var phpPro=\;` if this does it let me know and I'll post as answer for marking as solution. – shadow2020 Jun 04 '19 at 20:10
  • 1
    Possible duplicate of [How to pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – miken32 Jun 04 '19 at 20:17
  • It looks like `json_encode()` is getting an error, possibly because of Unicode characters in `$pro`, or maybe it contains a datatype that doesn't have a JSON encoding. – Barmar Jun 04 '19 at 20:22
  • @miken32 This code is the recommended way to accomplish it, but it's not working for some reason. How does that question help? – Barmar Jun 04 '19 at 20:23
  • What's in your array? – MER Jun 04 '19 at 20:24
  • Escaping the endcode returned with the page not working. I removed 2 fields and now getting ```Uncaught TypeError: Cannot read property '1' of undefined``` where am trying to display the data at ```alert(phpPro[i][1]);``` – wolfpride71 Jun 04 '19 at 20:34
  • The data is an auto-int, and 2 strings. I have an alert to display that displays the length of phpPro and it shows 0 so I assume that there are no records in the JS array. – wolfpride71 Jun 04 '19 at 20:44
  • I have this working now.I'm not sure how my sql changed but eventually it was not working. I tested the sql in in mysql, fixed it there and implemented in the webpage and all is working correctly. Thank you for the assist! – wolfpride71 Jun 05 '19 at 14:00

0 Answers0