How to escape Javascript code that is echoed in PHP - php

I have this code that is captured in the jquery Data object from a php page.
echo "
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
";
Problem is, the 's are not escaped. I have tried using /' to escape, but it comes up with an error. I am sure I am doing this wrong, does anyone know where to put the /' instead of '?

You could use a php nowdoc instead of quotes at all which would simplify things:
echo <<<'DOC'
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
DOC;
then use whatever you want inside (quote or dquote). This is, of course, unparsed so if $d was actually referring to a php var then you would have problems.

Your apostrophes actually look fine. But, within a double quoted string, PHP will evaluate any string beginning with a dollar sign as a variable and not produce the desired result. Try replace the jquery related instances of $ with \$. Like this:
echo "
var \$d = \$('<div/>', {
id: 'hi' + \$('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
\$('#textResp').append(\$d)
";

use json_encode function in php, it behaves like the escape_javascript function in rails.
just pass a string argument to the json_encode function, and it return the escaped string for you, see the sample code below:
<?php
$form_html = <<HTML
<form action='...' ...>
<input type='...' name='...' ...>
...
</html>
HTML;
?>
var form_html = <?php echo json_encode($form_html); ?>;
$('.remote#create_form').html(form_html).slideDown();

You will need to use \ before all 's.
However, this is puzzling, why do you feel you need escape characters? It appears you are simply echoing this output, if this is between <script /> tags, you should be fine.

PHP will attempt to expand variables, $name, that occur in strings wrapped in double quotes. Since $d looks like a variable to the PHP interpreter, it will try to replace it with the variable's value.
Assuming that you don't have $d defined anywhere, that will produce an empty space and, possibly, a notice (if you are using error level E_NOTICE).
To prevent that from happening, escape dollar signs with a backslash (replace $ with \$)

Use single quotes for your string construction. Only use double quotes when you specifically are including variables that you want evaluated. PHP is trying to evaluate all of those $ references you have in there. By using single quotes, you will avoid many escaping problems.
echo '
var $d = $("<div/>", {
id: "hi" + $("#textResp").children().length,
class: "eventdiv",
html: "hello"
}).hide().fadeIn(3000);
$("#textResp").append($d)
';

Related

Single quote within single quotes PHP

I have a HTML achor tag like below:
echo '<a href="javascript:tempBuy('.$res_get_price[0][0].','.$res_get_price[0][1].','.$res_get_price[0][2].','.$dt_str.')">'.$res_get_price[0][0];
And the corresponding javascript function tempBuy() is
function tempBuy(rate,veg_name,market_name,dt)
{
alert(dt);
}
But the problem is it does not alert at all ! May be I need to include the variable names within single quotes in tempBuy() function. I tried tempBuy(\'var1'\,\'var2\'...) but it shows error. How can I able to to that. Thanks .
Source for the part shows like this:
<td width="120px" class="">56.0
</td>
<script>
function tempBuy(rate,veg_name,market_name,dt)
{
alert(rate);
}
</script>
You didn't wrap your javascript arguments in quotes. You need to wrap each variable in single quotes, since you used double quotes for "href" attribute. Another thing is that you didn't close up "a" HTML tag.
echo ''.$res_get_price[0][0].'';
If there is anything in your variables that is not a valid javascript literal you have to make it a string like:
echo '<a href="javascript:tempBuy(\''.$res_get_price[0][0].'\' ...
If there are ' in your variables you have to replace them with \' as well.
As you can see form the rendered output, you need to quote the last 3 arguments which are non-numeric. The correct output should be: javascript:tempBuy(56.0,'Apple','Bangalore','2013-05-18')
The corrected PHP code is:
echo ''.$res_get_price[0][0].'';`
echo "<a href=\"javascript:tempBuy('".$res_get_price[0][0]."','".$res_get_price[0][1]."','".$res_get_price[0][2]."','".$dt_str."')\">".$res_get_price[0][0];

php javascript json parse escape characters

I currently have a webpage that need to use javascript to parse variables from php.
I do things like this:
data.notices = JSON.parse('<?php echo json_encode($notices) ?>');
However, when there is single or double quotes in the $notices variable, javascript console return errors.
How can I get the variables correctly?
This code doesn`t return error
<?
$notices = array('sad'=>'asd as" asd', 'asd"sdf '=>'asdasd" \' asd ads');
?>
<script>
data = new Object();
data.notices = JSON.parse('<?php echo addslashes(json_encode($notices)) ?>');
</script>
$a='b' will be converted to "b"(note the quotation mark) by json_encode
just write JSON.parse(<?php echo json_encode($notices) ?>);(remove ') will be ok.
I found that it is the problem caused by the fact that I did not escape the characters before inserting to database.
You are one extra operation. If you want message as javascript variable you can directly get like
data.notices = <?php echo json_encode($notices) ?>;
// and access like this
// data.notices[0] or data.notices['alert']

How to concatenate PHP and JavaScript strings with quotes to evaluate properly

I have one page iframed inside of another. The child page communicates with the parent page by using the sendMessage() function. The parent page runs eval() on the message that is received from the child page.
This is the code that constructs the message:
var msg_string = '$("body").append("<?php echo $content; ?>")';
var send_string = "sendMessage(\'" + msg_string + "\', '<?php echo $receiver_domain; ?>')";
setTimeout(send_string, <?php echo $delay; ?>);
The problem among other things is that the $content variable contains HTML and the double quotes in things like id="test" do not play well with all of this concatenation. I am at a loss trying to figure this out.
I have already attempted to escape the quotes in $content by converting them to " but that resulted in the browser placing div ids in double double quotes (""test"").
** Update **
Using the json_encode method does work for getting the data to the parent page. It's a much easier solution than what I had been doing (I had already accomplished this much but figured something was amiss). That said, the eval of the data still fails if there are double quotes in a div id="test". A string of just "test" works, but it actually puts "test" verbatim. This is the javascript source in the html after using the json method:
var msg_string = '$("body").append("<div class=\\\"test\\\">HEY WHATS UP<\/div>");';
var send_string = "sendMessage(\'" + msg_string + "\', 'http://domain.com')";
setTimeout(send_string,500);
This fails at the eval. Putting an alert in place of the eval yields this:
$("body").append("<div class="test">HEY WHATS UP</div>");
Any ideas?
** Update 2 **
So I FINALLY figured this out. It was a combination of the three answers below. The json answer tipped me off. Basically the double quotes needed to be tripple backslashed so that by the time it go to the eval, everything would be read properly.
I ran into a few other snags, including /r/n characters in the html...which I removed with str_replace and also an apostrophe...which was in an inner html element...I replaced that with the appropriate html entity and BAM!
Here is the code:
function escapeQuotes(string){
var quotes_regex = new RegExp("\"", "g");
return string.replace(quotes_regex, "\\\"");
}
var msg_string = '$("body").append(<?php echo json_encode( str_replace("\r\n", '', $content) ); ?>);';
var send_string = "sendMessage(\'" + escapeQuotes(msg_string) + "\', '<?php echo $receiver_domain; ?>')";
setTimeout(send_string,<?php echo $delay; ?>);
I upvoted everyone's answer since I used bits of everything. Thank you so much!
JSON is your friend.
var msg_string = '$("body").append(<?php echo json_encode($content); ?>)';
If your only concern is double quotes, why not just replace them with an escaped string?
var msg_string = '$("body").append("<?php echo str_replace("\"", "\\"", $content); ?>")';
I can't exactly test, but that would seem to work to me.
You need to escape using str_replace
$search = array("'", '"');
$replace = array("\'", '\"');
var msg_string = '$("body").append("<?php echo str_replace(search, replace, $content; ?>")';

Printing varchar php variable inside the javascript function

I am trying to print a variable value within the javascript function. If the variable is an integer ($myInteger) it works fine, but when I want to access text ($myText) it gives an error.
<?php $myText = 'some text';
$myInteger = '220';
?>
<script type="text/javascript">
<?php print("var myInteger = " . $myInteger . " ;\n");?> //works fine
<?php print("var myText = " . $myText . " ;\n");?> //doens't work
</script>
Can anyone explain to me why this happens and how to change it?
The problem with your code from the question is that the generated Javascript code will be missing quotes around the string.
You could add quotes to the output manually, as follows:
print("var myText = '". $myText. "';\n");
However, note that this will break if the string itself contains quotes (or new-line characters, or a few others), so you need to escape it.
This can be dealt with using the addslashes() function, among others, but this may still have issues.
A better approach would be to use PHP's built-in JSON functionality, which is designed specifically for generating Javascript variables, so it will do all the escaping for you correctly.
The function you're looking for is json_encode(). You'd use it as follows:
print("var myText = ". json_encode($myText). ";\n");
This will work with any variable type -- integer, string, or even an array.
Hope that helps.
Without more code we don't really know what you're trying to do or what error you're getting (or from where even), but if I had to guess:
If you are putting a string of text into a javascript variable, you probably need to quote it.
<?php print("var myText = '" . $myText . "' ;\n");?>
---^^^-------------^^^----
// Or even better:
<?php print("var myText = '$myText' ;\n");?>
ADDENDUM Per the comment below, don't use this if you expect your $myText to contain quotes.

echoing a jquery animation function with php

I am trying to echo this jquery function, with php. basically if the script detects a field of a form is not filled in then it will echo this and make the input text box turn red.
It works fine when it is not being echo'd.
echo('
<script type="text/javascript">
$(document).ready(function() {
$(\'input\').animate({backgroundColor:\"#F00\"},200);
});
</script>
');
any ideas?
I don't think you have to escape your quotes when the string is within single quotes. PHP won't parse the string, it will be output literally.
You're over-doing it on the string escape. To keep it simple, just use single quotes around the echoed string, and use double quotes inside it. Something like:
echo('
<script type="text/javascript">
$(document).ready(function() {
$("input").animate({backgroundColor: "#F00"}, 200);
});
</script>
');
When you're echoing stuff, there are indeed some cases when you need to escape the quotes, but most of the times you can simply get away with it by using different types of quotes. For example, I'll never get it why people still do something like:
echo "<input type=\"text\" name=\"username\">";
as opposed to
echo '<input type="text" name="username">';
which makes your life a whole lot easier when you have to modify it.
Hope this helps !
You shouldn't use \" there, just "
Furthermore: a hex-color-value is no numeric value you can use for animate() .
By this, the error is fixed by removing the backslashes from the doublequotes, but your animation wouldn't show any effect.
i didnt test it, but try that:
$nl = "\n";
echo '<script type="text/javascript">'.$nl;
echo ' $(document).ready(function() {'.$nl;
echo ' $("input").animate({backgroundColor:"#F00"},200);'.$nl;
echo ' });'.$nl;
echo '</script>'.$nl;
the $nl="\n" is only for linebreak (I prefer to use singlequotes in echos, so php didn't have to parse the content - just echo out).

Categories