PHP or JavaScript issue when parsing JSON encoded PHP array into JavaScripts JSON.parse()

977

I'm currently making a web app for my workplace, that downloads around 40,000 rows of data from an SQL table in one go, places the data into nested PHP arrays, and then attempts to echo the JSON encoded array, where a JavaScript variable should capture the contents.

If I attempt to echo the data straight into the tags, it works fine - everything is displayed perfectly - formatted as a JSON encoded string. If, however, I attempt to echo the data into<script> tags, between speech marks '' or "", it throws an error in chrome, saying 'Uncaught SyntaxError: Unexpected identifier' - and when I attempt to scroll to the end of the (very long) string, it appears to have been chopped off, only a few thousand characters in.

The string is actually 1,476,075 characters long.

How do I get around this? I'm remaking the application - it originally basically combined javascript with the SQL results whilst iterating through the results rows, but this was so slow and clunky, so I figured an easier and quicker way to move the data from PHP to JavaScript, would be with a large JSON encoded string.

Any advice would be greatly appreciated.

  • Dan.
222

Answer

Solution:

json_encode() takes care of ALL the quoting/escaping that needs to be done:

<?php
    $foo = 'this is a simple string';
?>

<script>
    var foo = "<?php echo json_encode($foo); ?>"; // incorrect
    var bar = <?php echo json_encode($foo); ?>; // correct

The above construct would create:

var foo = ""this is a simple string"";
          ^--- your quote
           ^---the quote json_encode added

var bar = "this is a simple string"; // all-ok here.

People are also looking for solutions to the problem: MySQL and PHP performance of multiple queries

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.