-3

I am trying to echo a multidimensional array from PHP to js, but it is giving me an error saying that "<" is an unexpected token.

js

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

Php

<?php
    // PHP array
    $products = array(
        // product abbreviation, product name, unit price
        array('choc_cake', 'Chocolate Cake', 15),
        array('carrot_cake', 'Carrot Cake', 12),
        array('cheese_cake', 'Cheese Cake', 20),
        array('banana_bread', 'Banana Bread', 14)
    );
?>
Seesi L
  • 113
  • 6
  • Is this the answer to your question? [convert-php-array-to-javascript](https://stackoverflow.com/questions/5618925/convert-php-array-to-javascript) – Lam Tran Duc Dec 10 '21 at 01:53
  • Your `.js` file is *probably* not processed on your server as PHP source code. Thus it is sent with that ` – Pointy Dec 10 '21 at 02:02
  • How is the JS code imported into the page? You did not show that. Is it a ` – Pointy Dec 10 '21 at 02:09
  • Duplicate of [How do I pass variables and data from PHP to JavaScript?](/q/23740548/4642212). – Sebastian Simon Dec 10 '21 at 05:22

1 Answers1

1

missing ;:

var products = "<?php echo json_encode( $products ); ?>";

also:

In order for the var... line to be parsed, that line MUST be loaded within <script> in a PHP file, not within a separate JS file, which does not get parsed via PHP at all

Ron
  • 5,900
  • 2
  • 20
  • 30
  • The missing semicolon could not possibly cause the reported error, and usually semicolons are not required in JavaScript. – Pointy Dec 10 '21 at 02:04
  • 1
    semicolumn is within PHP, not in JS. And it can cause a PHP error – Ron Dec 10 '21 at 02:05
  • The OP says that that line of code is JS code. – Pointy Dec 10 '21 at 02:05
  • if the OP outputs the expected JS without encapsulating it within "", that would cause the next line to brake JS. – Ron Dec 10 '21 at 02:07
  • If that really is a separate JS file loaded from a ` – Pointy Dec 10 '21 at 02:08
  • that is true, bit is not clear what he is loading, how, and where... so I am doing a best attempt to answer – Ron Dec 10 '21 at 02:09
  • Agreed, @Ron, it is not clear. – Pointy Dec 10 '21 at 02:10