April 3, 2012

Having trouble passing text from MySQL to a Javascript function using PHP

Question by Nate

So here’s the problem. I have data in a MySQL DB as text. The data is inserted via mysql_real_escape_string. I have no problem with the data being displayed to the user.

At some point I want to pass this data into a javascript function called foo.

// This is a PHP block of code
// $someText is text retrieved from the database

echo "<img src=someimage.gif onclick="foo('{$someText}')">";

If the data in $someText has line breaks in it like:

Line 1
Line 2
Line 3

The javascript breaks because the html output is

<img src=someimage.gif onclick="foo('line1
line2
line3')">

So the question is, how can I pass $someText to my javascript foo function while preserving line breaks and carriage returns but not breaking the code?

===========================================================================================

After using json like this:

echo "<img src=someimage.gif onclick="foo($newData)">";

It is outputting HTML like this:

onclick="foo("line 1<br />rnline 2");">

Which displays the image followed by rnline 2″);”>

Answer by Cal

json_encode() is the way to go:

$json = json_encode($someText); # this creates valid JS
$safe = HtmlSpecialChars($json); # this allows it to be used in an HTML attribute
echo "<img src=someimage.gif onclick="foo($safe)">";

You can see a demo here: http://codepad.org/TK45YErZ

Answer by Starx

Only json_encode() is enough to escape the new line

echo "<img src=someimage.gif onclick="foo(".json_encode($newData).")">";

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!