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).
Related
Hello dear programmers,
I have a problem with the echoing of a html phrase with an onclick function that executes a javascript function. I want to build a tabpage, for a image gallery.
The echo:
echo "<div class='albumitem'><a class='tablinks' onclick='openAlbum(event, '".$album."')'><h1 class='galleryheader'>".$album."</h1></a><div id='".$album."' class='tabcontent'>";
Everything goes well, except the passing of the variable in the onclick function, as you can see here. What actually the HTML looks like:
<a class="tablinks" onclick="openAlbum(event, " aubing')'=""><h1 class="galleryheader">Aubing</h1></a>
But this onclick event has to look like this:
onclick="openAlbum(event, 'Aubing')"
Is there a way to actually realise this or do I have to find an other option?
I actually tried switching " with ', didnt go very well....
Thank you for everybody that tries to help
Try this:
echo "<div class='albumitem'><a class='tablinks' onclick='openAlbum(event, \"$album\")'><h1 class='galleryheader'>".$album."</h1></a><div id='".$album."' class='tabcontent'>";
see escaped double quotes in the onclick definition
addslashes is what you are looking exactly.And also you have to remove the single quotes in variable.Try to do the following way.
echo "<div class='albumitem'><a class='tablinks' onclick='openAlbum(event, '".addslashes($album)."')'><h1 class='galleryheader'>".$album."</h1></a><div id=".addslashes($album)." class='tabcontent'>";
Hope this help.
An alternative:
$escapedString = htmlspecialchars('This is a test string: < > & \' " end.', ENT_COMPAT);
echo "<div onclick='alert(this.dataset.name)' data-name=\"$escapedString\">Click Me</div>";
This approach avoid quotes inside function, no quotes nesting.
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];
I am using the shortcode execute plugin in wordpress.
This simply allows me to write shortcode like this [email_spamproof]
But I am trying to echo a script. Please see below...
<?php
echo '<script type="text/javascript">
<!--
// spam protected email
emailE=("enquiries#" + "example.co.uk")
document.write('<a title="E-mail Example" href="mailto:' + emailE + '">' + emailE + '</a>')
//-->
</script>
<noscript>
<span class="spam-protected">Email address protected by JavaScript. Please enable JavaScript.</span>
</noscript>';
?>
Now you can probably see my problem already.
Usually when I echo stuff it goes like this... echo 'hello';
And you break the string using the same apostrophes
- like this... echo 'hello ' . php_name() . ' and friends'
My Problem
The script also uses a similar method by adding script variables into the string, but these script apostrophes will get confused as PHP apostrophes, and break the echoed string.
How can I avoid this?
Thanks
The right code:
<?php
echo "<script type='text/javascript'>
<!--
// spam protected email
emailE=('enquiries#' + 'example.co.uk')
document.write('<a title='E-mail Example' href='mailto:' + emailE + ''>' + emailE + '</a>')
//-->
</script>
<noscript>
<span class='spam-protected'>Email address protected by JavaScript. Please enable JavaScript.</span>
</noscript>";
?>
The \ character is the escape character. Prepend one to each internal use of the character used to delimit the string.
Alternatively, use a HEREDOC.
It is easy. Save your javascript code in a new one file and then use this to load it:
include('myjavascript.php');
Then you will use the include option as a echo because the web will understand your code as HTML and you execute it when you want with php (like echo).
You could write " in your javasript code, and then only use single quotes(') in your php echo.
A more suitable method is to use escape characters in your javascript code "\'" (without the double quotes)
You can either escape them with a back slash: echo 'It\'s cold'; or use heredoc:
echo <<<END
lots of text here
END;
You need to escape them and then concatenate the variables :
(Also I dont know if you realize, but you are echoing a commented out section of javascript)
echo '<script type="text/javascript">
<!-- // spam protected email
emailE=("enquiries#" + "example.co.uk")
document.write(\'<a title="E-mail Example" href="mailto:'.emailE.'">'.emailE.'</a>\')
//-->
</script>
<noscript>
<span class="spam-protected">Email address protected by JavaScript. Please enable JavaScript.</span>
</noscript>';
How should I quote this:
<tr onclick="$.colorbox({href:'information1.html'});">
When put in an echo " "; ?
I have tried this:
echo "<tr onclick='$.colorbox({href:'information1.html'});'>";
Which shows a Jquery error.
And I tried this:
echo "<tr onclick="$.colorbox({href:'information1.html'});">";
Which shows a PHP error.
Any workarounds? Thanks
You need to escape the quotes symbols:
echo '<tr onclick="$.colorbox({href:\"information1.html\"});">'
Note that using inline script is not considered to be a good practice!
echo '<tr class="foo">'
In the javascript code:
$('.foo').click(function() {
$.colorbox({ href: "information1.html" });
});
Simply escape the quotes. Whilst on this subject I feel it important to mention the fact that generally speaking, you should use single quotes for 'code' and double quotes only for displayed strings.
This stems from C standards and keeping this consistent will help you in the future if for example you wanted to implement gettext() and translate your website into multiple languages.
echo '<tr onclick="$.colorbox({href:\'information1.html\'});\">';
Having said that, there's a better way to achieve what you're doing. Give the row an id:
<tr id="inforow" />
And use jQuery to bind to it's click event when the DOM is ready.
$(document).ready(function() {
$(".inforow").click(function() {
$.colorbox({href:'information1.html'});
});
});
Anytime you want to print a string with a quote in it, just use the escape character '\' to ignore the quote as a literal closing quote, like so:
echo "<tr onclick=\"$.colorbox({href:'information1.html'});\">";
echo "<tr onclick=\"$.colorbox({href:'information1.html'});\">";
echo "<tr onclick=\"$.colorbox({href:'information1.html'});\">";
Try that:
echo "<tr onclick=\"$.colorbox({href:'information1.html'});\">";
I would use PHP-methods instead of caring about the quotes
echo '<tr onclick="'.
htmlentities('$.colorbox('.json_encode(array('href'=>'information.html'))).')">';
...will always create proper JSON and proper HTML, no matter what characters you use.
NO NEED to quote it.
NO NEED to put in an echo " ";
Just leave it AS IS:
?>
<tr onclick="$.colorbox({href:'information1.html'});">
<?
as well as any other HTML.
It's PHP. It's embedded in HTML. You can leave PHP mode any time
Another way is using EOD
$string = <<<EOD
"duble quotation" and 'quotation' all enable
EOD;
echo $string;
lets imagine a form editor, it can edit available values. If the data contains " character (double quote) it "destroys" HTML code. I meant, lets check the code: so I generate HTML:
onclick="var a = prompt('New value: ', '<?php echo addslashes($rec[$i]); ?>'); if (a != null)....
and it results in
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
and this makes JS work impossible, so that it ruins the code. With single qoute ' it works OK. mysql real escape does the same.
How to escape any string so that it won't ruin javascript?
json_encode looked OK, but I must be doing something wrong, its still bad: heres a screenshot how Firefox sees it - it inserts a "bad" double quote! The value is just a simple number:
http://img402.imageshack.us/img402/5577/aaaahf.gif
and I did used:
('Ird be az új nevet:', <?php echo json_encode($rec['NAME']); ?>); if (a) {
The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:
<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';
That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
Your problem is highlighted in bold.
You can't quote a variable declaration
you shouldn't need to escape the double quote once this is removed since it is within single quotes.
Should look like this -
onclick="newFunc();"
<script>
function newFunc() {
var a = prompt('New value: ', 'aaaa"aaa');
if (a != null) { v....
}
</script>
...onclick="new_func();"...
<script>
function new_func() {
var a = prompt('new value:','<?php code; ?>');
if (a) { <!--javascript code--> } else { <!--javascript code--> }
}
</script>
I'm really just re-wording what #Marshall House says here, but:
In HTML, a double quote (") will always end an attribute, regardless of a backslash - so it sees: onclick="var a = prompt('New value: ', 'aaaa\". The solution that #Marshall offers is to separate your code out into a function. This way you can print escaped PHP into it without a problem.
E.g.:
<script>
// This is a function, wrapping your code to be called onclick.
function doOnClickStuff() {
// You should no longer need to escape your string. E.g.:
//var a = prompt('new value:','<?php echo $rec[$i]; ?>');
// Although the following could be safer
var a = prompt('new value:',<?php json_encode($rec[$i]); ?>);
if (a) { <!--javascript code--> }
else { <!--javascript code--> }
}
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->