Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.
share|improve this question
1  
If it's JSON-encoded, you don't need quotes. Just drop it directly into JavaScript code in your <script> tags. –  Pointy Jul 31 '14 at 15:15
    
I'm passing it into JSON.parse() - I'm pretty sure it needs to be encapsulated in quotation marks. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… –  Daniel Price Jul 31 '14 at 15:17
2  
There's no need to pass it into JSON.parse(), that's the point - JSON syntax is valid JavaScript syntax. That's what the J in JSON stands for. –  Pointy Jul 31 '14 at 15:18
    
How would I capture the array that it's held in? –  Daniel Price Jul 31 '14 at 15:20

1 Answer 1

up vote 2 down vote accepted

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.
share|improve this answer
    
I understand now, thank you. I've only been using JavaScript for a few months now, but I should have figured that one out. Thank you all, very much! –  Daniel Price Jul 31 '14 at 15:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.