I am doing the following:
var test = <? echo $variable; ?>
and I want to append test:
$("#div").append(test);
My problem is that $variable might have '' or "" within it self. This means variable can be, for example
$variable = "<div style='some:style;'>Some test</div>"
So, when I put this in javascript it becomes
$("#div").append(<div style='some:style;'>Some test</div>)
without double quotes (throwing an error), which I try to improve:
$("#div").append("'"+<div style='some:style;'>Some test</div>+"'")
which won't work either way with ' ' or " " because it breaks the specials within the string fragment, stopping ' or "... can someone walk me through how this can be done?
EDIT
I'm sorry MY BAD my problem is that $variable actually has a function called inside, so that's how it becomes:
$("#div").append(<div onclick="some_function('string parameter')" style='some:style;'>Some test</div>)
That's it. How exactly can I do this?
Use json_encode:
$variable = json_encode("<div style='some:style;'>Some test</div>");
or with the function:
$variable=json_encode('<div onclick="some_function(\'string parameter\')" style="some:style;">Some test</div>');
Related
All PHP generated Javascript Code I’ve done works, but this doesn’t … any idea?
echo "E-Mail an $row[firma] senden …<br />\n";
I’ve tried everything … print <<<HTML, print <<<JS … other quotes (single quotes, no quotes) … it just executes an HTML link …
It's hard to be sure - what's the value of $r and $row? Which part isn't working? What is the actual output of the markup, when you view the source? Are there any javascript errors in the Web Developer console?
I will make an assumption that $r and $row are valid PHP variables in this context, and that the linkTo_UnCryptMailto() javascript function exists.
I also note that the firma key is not enclosed in quotes - I am going to assume that's a typo.
Try simplifying the code and not parsing the variables within a "double quoted" string:
echo 'E-Mail an ' . $row['firma'] . ' senden …<br />';
From within PHP, I want at a certain point to change the content of a DIV called "menu".
In PHP, I do the following:
echo "<script> document.getElementById(\"menu\").innerHTML = \"NewContent\"; </script>";
And it perfectly works.
Then, things get more complicated, and I have a function that "creates" a piece of HTML, like this:
function createNewDiv() {
$o = "Click 'here'";
$o. = "<i onclick=\" $(\"#maindiv\").load('another.php'); return false; \">XXX</i>";
$o .= "<b>... and much, much more...</b>";
return $o;
}
In another area of the page, I do:
echo createNewDiv();
and it prints nicely, no syntax error whatsoever.
If I now try to do something like this:
echo "<script> document.getElementById(\"menu\").innerHTML = \"".createNewDiv()."\"; </script>";
it stops working with some syntax error (from the browser) due to strings that are interrupted "somewhere" by some quotes/double quotes.
I guess I must escape the quotes/double quotes somehow, I tried with addslashes() but it did not work.
Then I realized I only needed to escape the double quotes, so I did
$escaped = str_replace("\"", "\\\"", createNewDiv());
echo "<script> document.getElementById(\"menu\").innerHTML = \"$escaped\"; </script>";
But still it doesn't work! I know it's a truncated string somewhere, but unfortunately I cannot access the source because it's in an AJAX-updated div and the browser only shows me the main page.
I am just going mad thinking about the first function output, going into the str_replace, then into innerHTML, then printed by PHP, then interpreted by the browser... And I get lost "where" the quotes should be escaped ;)
You have nested double-quotes in:
$o. = "<i onclick=\" $(\"#maindiv\").load('another.php'); return false; \">XXX</i>";
It outputs:
<i onclick=" $("#maindiv").load('another.php'); return false; ">XXX</i>
Replace inner double quotes (around #maindiv) with single quotes:
<i onclick=" $('#maindiv').load('another.php'); return false; ">XXX</i>
or replace nested double-quotes with the " entity:
<i onclick=" $("#maindiv").load('another.php'); return false; ">XXX</i>
To make such replacement automatically, use the PHP's built-in htmlspecialchars() function.
By the way, during debug, it's generally a good idea to separate client side from server side. First make static HTML working, then convert it to a server-side scripted one. And consider using a template engine instead of hardcoding HTML into PHP code.
I've got some issues. I have javascript function with variables, but when the description is with symbols like - "Description's" that - '. It ruins my code, how could i fix it. Here is my code:
onClick="javascript:insertData('
.$currentTasken.', \''.$currentDate.'\', '
.$currentUser.', \''.$currentSummary.'\', '
.$currentAsPercent.', \''.$currentDescription.'\');"
I used \''.$currentSummary.'\' like this, but still having some issues if that text has this symbol ' . I havent tried other but I think it would be the same. Help.
I assume that the snippet you show in your post is within a PHP section. In that case onClick should really be $onclick (i. e. a valid PHP variable name). Otherwise you could do the whole thing inside a html section.
<?PHP
// first mask all dangerous "'" as "\\'" within the variables:
foreach (array('currentTasken','currentDate','currentUser','currentSummary',
'currentAsPercent','currentDescription') as $v )
$$v=str_replace("'","\\'",$$v);
?>
<!-- some type of html tag ... whatever it might be in your case -->
<input type="button"
onClick="javascript:insertData<?PHP echo
"('$currentTasken','$currentDate','$currentUser','$currentSummary',"
."'$currentAsPercent','$currentDescription')"; ?> >
In PHP strings within " will allow for variables to be evaluated inside. You don't have to concatenate the string with .s.
I want to update innerhtml of div with id NotifyDiv
I want to change it with following html code.
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
I am using following code to change it.
echo "<script>document.getElementById('NotifyDiv').innerHTML='$html'</script>";
But no changes occur.
However it I remove id = 'js-news' from the above ul tag it works.But I'll need the id.
If you check the source code of your browser you will see this:
<script>document.getElementById('NotifyDiv').innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'</script>
So we can see that in the JavaScript string you are using apotrophes, but the string is already encloded with apostrophes, so it attempts to end the string early: (before the letter j in js-news)
'<ul id='js-news'><li>HELLO WORLD!</li></ul>'
This can be solved by using escaped quotation marks for the JS string:
echo "<script>document.getElementById('NotifyDiv').innerHTML=\"$html\"</script>";
Basically, the code you have causes a syntax error in JS:
echo "...innerHTML='$html'</script>";
expands to:
// opening ' closing ' => js-news === syntax error!
// \/ \/
echo "...innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'</script>";
Resulting JS code:
document.getElementById('NotifyDiv').innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'
The syntax highlighting shows the problem
Note the single quotes around $html and the single quotes inside the $html string. The best way to echo PHP values in JS would be to use json_encode:
echo "...document.getElementById('NotifyDiv').innerHTML=", json_encode($html), "</script>";
The output should be something like:
<script>document.getElementById('NotifyDiv').innerHTML="<ul id='js-news'><li>HELLO WORLD!<\/li><\/ul>"</script>
Now, those slashes are escaped, and you probably don't want that. Thankfully, there's a second parameter you can pass to json_encode: cf the docs. Passing JSON_UNESCAPED_SLASHES is what you need to do here:
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
echo "<script>document.getElementById('NotifyDiv').innerHTML=".json_encode($html, JSON_UNESCAPED_SLASHES)."</script>";
The output:
<script>document.getElementById('NotifyDiv').innerHTML="<ul id='js-news'><li>HELLO WORLD!</li></ul>"</script>
DEMO
Perfect ans to your query is as under (just copy n paste and check it)
<?php
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
?>
<script type="text/javascript">
document.getElementById('NotifyDiv').innerHTML="<?php echo $html; ?>";
</script>";
You need to pass PHP variable with PHP syntax that is <?php ?>
Even if we can mix PHP, JavaScript and HTML together, we need to initialize proper languages before using their variables in case of JavaScript and PHP.
So, final code should be:
echo "<script>document.getElementById('NotifyDiv').innerHTML = '<?php echo $html;?>'</script>";
Otherwise, everything looks correct.
I am trying to store php value in my javascript variable. But this code is giving me syntax error. Is the code correct ?
var b = <?php echo $tagValue;?>;
alert("B is " +b);
You have to make sure that your webserver interprets that file as a php file. then you have to adapt your code, because it looks like you could have an error in your js code in the end:
var b = "<?php echo $tagValue;?>";
alert("B is " +b);
(I have added quotes). Does not apply, if you are sure that $tagValue is only numeric.
In case you don't really know what kind of value your $tagValue is or you simply want to make sure you won't fail you should use json_encode($tagValue):
var b = <?php echo json_encode($tagValue);?>;
alert("B is " +b);
Please note that in case $tagValue is an array/object your js-alert won't be very usefull :)
Easiest way i've found to do it without worrying about character escaping or XSS is to convert the contents of the variable to JSON. All it takes is to echo json_encode($tagValue); instead of echo $tagValue;
make a function maybe can help u.
this is an example
// your php code
$tagValue = 'value';
getValue($tagValue);