0

I have a series of data that I want to put inside an array in a javascript. I use Wordpress as a cms, and my data looks like this (the content of the post):

line1
line2
line3

However when i try to seek data from the post I see this code in javascript for let's say 3 posts:

var locations=['line1
line2
line3','line1
line2
line3','line1
line2
line3'];

I receive this error when I look in the console: Uncaught SyntaxError: Unexpected token ILLEGAL. I have searched here a lot of answers but I did not succeed into breaking a leg with it. However I had a look in the HTML tab of the content there is no <br/>, so the new line is not html code.

I also tried to escape special characters in php like this, but it pops out the same error:

echo '\''.htmlspecialchars (get_the_content()).'\',';

However, if the content is in one line, like 'some text' it appears to run ok.

Any ideas?

Thank you!

4
  • Can we format the data, clean out the special characters before running it through the PHP script? Commented Mar 1, 2012 at 20:54
  • I guess so ... how would you do that? I am running a get_posts( $args ) in a very basic way, so no complicated stuff is there. Commented Mar 1, 2012 at 20:57
  • This means there's nothing you can do about the input before it is submitted to the server, right? You are working with PHP only. There's already an answer for you. Commented Mar 1, 2012 at 21:00
  • Actully the content has to be in that way. Commented Mar 1, 2012 at 21:13

2 Answers 2

2

Use json_encode() to turn it into a JavaScript literal before outputting it.

Sign up to request clarification or add additional context in comments.

1 Comment

Good one, but the content was displayed in one line. I finally made this array_push( $locations, nl2br ( get_the_content()) ); and then echo 'var locations='. json_encode($locations).';' which did the job very well.
1

Actually this is a php question. Javascript have no way to "recover" from such syntax errors by itself.

echo "'".str_replace(
    array("'", "\n", "\r"),
    array("\\'", "\\n", "\\r"),
    get_the_content()
)."'";

2 Comments

Actually for this I think nl2br works better, but thank you for the starting point!
Yes, if you want to output it into html. After all, idea with json_encode is better.

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.