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

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 \/>\r\nline 2");">
Which displays the image followed by \r\nline 2");">

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

If I'm not interpreting badly you may do this:
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{".trim( preg_replace( '/\s+/', ' ',$someText ) )."}')\">";

You'll save yourself a lot of headaches by pulling the JavaScript out of the HTML:
<img id="myImage" src="someimage.gif"/>
<script type="text/javascript">
var str = <?php echo json_encode($json); ?>;
document.getElementById('myImage').addEventListener(
'click',
function() {
foo(str);
}
);
</script>
Or something similer...

Only json_encode() is enough to escape the new line
echo "<img src=someimage.gif onclick=\"foo(".json_encode($newData).")\">";

Related

Is it possible to change original html text in php?

I am trying to make "manner friendly" website. We use different declination dependent on gender and other factors. For example:
You did = robili
It did = robilo
She did = robila
Linguisticaly this is very simplified (and unlucky) example! I would like to change html text in php file where appropriate. For example
<? php
something
?>
html text of the page and somewhere is the word "robil"
<div>we tried to robil^i|o|a^</div>
<? php something ?>
Now I would like to replace all occurences of different tokens ^characters|characters|characters^ and replace them by one of their internal values according to "gender".
It is easy in javascript on the client side, but you will see all this weird "tokenizing" before javascript replace it.
Here I do not know the elegant solution.
Or do you have better idea?
Thanks for advice.
You can add these scripts before and after the HTML:
<?php
// start output buffering
ob_start();
?>
<html>
<body>
html text of the page and somewhere is the word "robil"
<div>we tried to robil^i|o|a^, but also vital^si|sa|ste^, borko^mal|mala|malo^ </div>
</body>
</html>
<?php
$use = 1; // indicate which declination to use (0,1 or 2)
// get buffered html
$html = ob_get_contents();
ob_end_clean();
// match anything between '^' than's not a control chr or '^', min 5 and max 20 chrs.
if (preg_match_all('/\^[^[:cntrl:]\^]{3,20}\^/',$html,$matches))
{
// replace all
foreach (array_unique($matches[0]) as $match)
{
$choices = explode('|',trim($match,'^'));
$html = str_replace($match,$choices[$use],$html);
}
}
echo $html;
This returns:
html text of the page and somewhere is the word "robil" we tried to
robilo, but also vitalsa, borkomala

Weird passing php string to javascript sometimes not work

how i what it to work:
goal: make a album viewer without reload the page, with a img html element, change img SRC dynamically with javascript, but image url's stored in php variables and what copy to javascript array.
Problem: example have album where have 17 picture, if i echo in php then $i count from 1-17 but in javascript count to 2-12 and 15-17 so ignore 1,13,14 etc. have no ideea why because no difference in data, so DataPicId[13] is undefined but 15th index or 12th index got value normally.
while($row = mysql_fetch_array($SQLpic))
{
$i=$i+1;
$PicId=$row['id'];
$Url=$row['url'];
$Desc=" ".$row['description'];
$UpUser=$row['uploader'];
$Update=$row['udate'];
echo"<script>
nr=Number('".$i."');alert(nr);
DataPicId[nr]=Number('".$PicId."');
DataPicUrl[nr]='".$Url."';
DataPicDesc[nr]='".$Desc."';
DataPicUser[nr]=Number('".$UpUser."');
DataPicDate[nr]='".$Update."';
alert(DataPicUrl[nr]);
</script>";
$ThumbUrl=GetNameOnly($Url);
echo "<div id='PicBoxOut'>
<div id='PicBoxIn' onclick=SelectSrc('".$i."');>
<a href='javascript:void(0);'>
<img src='".$ThumbUrl."' border='0'></a>
</div></div>";
Without seeing the generated html / javascript, I would guess that your variables are breaking your javascript. That could be for example a single quote in the description of a photo.
To make sure that you output valid javascript, it is better to send your complete row-set to javascript as json and build your html in javascript using that json.
So something like:
<?php
// Note that normally you would have done this already in a controller
// and not when you are outputting html
$rows = array();
while($row = mysql_fetch_array($SQLpic))
{
$rows[] = $row;
}
?>
<script>
var json = <?php echo json_encode($rows); ?>,
object = JSON.parse(json);
// now `object` will contain all your rows in a javascript object / array
</script>

How can I insert text in an html element stored in a variable?

I have a program which is copying the text from another website and showing it.
It is storing the text in a variable $string.
The variable is containing html tags in it and I want to add text before a html tag stored in the variable.
For example: $string="<div id='1'><div id='game'></div>"; I want to add text before the div whose id is game.
To add the text before the div whose id is 'game'. simply use:
$string = "<div id='1'><div id='game'></div>";
$new = "texttoinsert";
$pos = "<div id='game'></div>";
echo str_replace($pos, $new.$pos ,$string);
In php the easiest way to do this would be using str_replace (http://www.php.net/manual/en/function.str-replace.php).
$textToInsert = "test";
$string = str_replace("<div id='game'>", $textToInsert."<div id='game'>" ,$string);
For that particular case the following works:
$($string).prepend("text");
DEMO
Using jQuery the solution is simple:
var text = $("<div id='1'><div id='game'></div></div>");
$('#1', text).prepend('text-to-insert');
and the result HTML can be obtained like this: text.html()
I hope this help.

Store data in html element

I have dynamic content which I generate with PHP, and i want to store some various text in data attribute. Bu the problem is that i need to escape various characters that could damage my entire html
So I need to do some kind of encoding with php and then decode that string with javascript when i want to use that data, what would be the best way to do that?
And just to clarify i do not want to use any inputs or anything like that, i need to store this data in various elements for example a or div and so on...
If all you want is to pass some data to JavaScript, why not just write it directly to a variable:
<html>
<head>
<script>
var data = <?php echo json_encode($data); ?>
</script>
<!-- etc. -->
Anyway, if you want to do it your way, you can use htmlspecialchars to escape arbitrary data before putting it in an HTML attribute:
<div data="<?php echo htmlspecialchars('"\'!)(#UI#_!)(#JP_!()#J'); ?>">Example</div>
If you then read that with JavaScript, it should understand the HTML encoding, so you won't need to do anything special to read it.
If your data is more complex, but not binary, you could JSON encode it, then use htmlspecialchars:
<?php
$data = array();
$data["a"] = 123;
$data["b"] = "example";
$jsonData = json_encode($data);
$escapedJsonData = htmlspecialchars($jsonData);
echo "<div data=\"$escapedJsonData\">example</div>";
?>
You can then read that data in JavaScript using JSON.parse:
var yourDiv = getDivSomehow();
var data = JSON.parse(yourDiv.getAttribute("data"));
If your data is binary, you can base64 encode it:
<?php
$data = someImage();
$encodedData = base64_encode($data);
echo "<div data=\"$encodedData\">example</div>";
?>
Presumably there's some way to decode this in JavaScript.

PHP javascript call with PHP variable

Good day, I am having a very odd error with my PHP code. I am attempting to dynamically change the content of my webpage by reading from an xml file. I read in some data and assign the data to a PHP variable called $course_title and then attempt to call some Javascript that will update the "innerHTML" of a DOM element. Note: on the line "echo $course_title;' that prints out the correct data to the screen.
$fn = dirname(__FILE__)."/course.xml";
$xml = simplexml_load_file($fn);
$course_bookimagelocation = "";
foreach ($xml->children() as $child)
{
if($child[0]->getName()=="book")
$course_bookimagelocation = $child;
if($child[0]->getName()=="title")
$course_title = $child;
}
//Problems start here...
echo $course_title;
echo '<script type="text/javascript">document.getElementById("heading").innerHTML = "';
echo $course_title;
echo '";</script>';
What is very unique is that the first echo statement prints the correct information, but the next three lines, the .innerHTML does not get changed to that same value. Does anyone know what that is? What is also weird is that if I replace the second "echo '$course_title';" with something like 'Hello world!' then "Hello World!" appears as the innerHTML of the "heading" id object.
EDIT
In the XML file called course.xml, the title element is IC 210 Fall 2010 and the contents of $course_title is IC 210 Fall 2010 so the parsing of the php file appears to be correct and there does not seam to be any special characters like a " or '
I also tried putting everything on the same line and not luck... (I even made sure in the xml file that the <title> element had the text on the same line...
Make sure that .innerHTML = "Some text" are on the same line because .innerHTML = "\nSome Text\n" won't work in javascript.
If you want to have something like this:
.innerHTML = "
Some String
";
try:
.innerHTML = ""+
"Some String" +
"";
"call some Javascript that will update the "innerHTML" of a DOM element." for that we use AJAX, no?
well you can do that way but i think it would be simpler to have the text preloaded in some hidden DIV's and use your functions just to change content's of the DIVS or even toggle visibility of the DIV (as you prefer). That way you will avoid many escaping problem's referred in the comments.
that's the way i would do it if not to use AJAX

Categories