JS inside PHP Escape String (for functions) - php

I have a PHP script that generates some Javascript for me in a manner like this:
foreach ($array as $element)
{
echo '<a onClick="myFunctionTakesPHPValues('.$element[0].','.$element[1].')">'.$element[2].'</a>';
}
My problem is that how can I escape so that the Javascript bit will look more like
<a onClick='MyFunctionTakesPHPValues("'.$element[0].','.$element[1].'")>'.$element[2].'</a>';
I hope this makes sense. The short version is that I feel i need triple quotes inside double quotes inside single quotes, but there is no such thing as triple quotes, but I believe there is some way to escape quotes to nest it up three times.

Same as always: encode as JSON.
echo '<a onClick="myFunctionTakesPHPValues('.json_encode($element[0]).','.json_encode($element[1]).')">'.$element[2].'</a>';

Never echo JS from PHP. Escape from PHP mode instead, it will save you a lot of slashes and nerves.
Every value have to be escaped properly, as explained in this article
So, for the JS values you have to escape them with json_encode() and, as they are going into HTML attribute, escape them as HTML too.
For the last element only HTML encoding is required.
foreach ($array as $element)
{
$param1 = htmlspecialchars(json_encode($element[0])); // better give them
$param2 = htmlspecialchars(json_encode($element[1])); // meaningful names
$param3 = htmlspecialchars($element[2]);
?>
<a onClick="myFunctionTakesPHPValues(<?=$param1?>,<?=$param2?>)">
<?=$param3?>
</a>
<? }
And yes, using raw JS in HTML attributes considered as a bad practice.

Use Like
echo "<a onClick='myFunctionTakesPHPValues(\"".$element[0]."\",\"".$element[1]."\")'>".$element[2]."</a>";

Use this:
echo "<a onClick='MyFunctionTakesPHPValues(\"'".$element[0]."','".$element[1]."'\")>'".$element[2]."'</a>'";

foreach ($array as $element)
{?>
<a onClick="myFunctionTakesPHPValues("<?php echo $element[0].','.$element[1].')>'.$element[2].'</a>'
}
?>

Related

Echo a html phrase, with onclick function

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.

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];

jQuery string is not defined

I'm sending data to function by onclick event but I can't get string value I just getting integer value, it say that 'value' is not defined. what is the problem.
My code is:
<a href="javascript:void(0)"
onclick="begin(<?php echo $data['user_id'];?>,
<?php echo $data['name'];?>);">
This is my function:
function begin(id,name)
{
alert(id);
alert(name);
}
I'm not getting name value, if I pass hard-code string then its also not getting here only integer are accessible.
You need to wrap your parameters in quotes to make it a string.
<a href="javascript:void(0)" onclick="begin('<?php echo $data['user_id'];?>','<?php echo $data['name'];?>');">
As Matt says, without quotes it won't be recognised.
That said, I don't think his answer is correct. I would prefer this code: (whitespace added for legibility)
<a href="javascript:void(0);" onclick="begin(
<?php echo htmlspecialchars(json_encode($data['user_id'])); ?>,
<?php echo htmlspecialchars(json_encode($data['name'])); ?>
);">
json_encode (docs) is good for passing any PHP variable (except Resources) into JavaScript. In this case, it will add quotes around the string, and escape characters as needed with backslashes. Since it's going in an attribute, you need htmlspecialchars to convert symbols to be safely insertable.

php echo a hyperlink with javascript confirm function

I have been using this code for deleting data from database. What i wan is whenever a user clicks an image link to delete data from the confirm function prompts up and ask for action, i am getting error in this code.
$delurl = "delete_dish.php?dish_id=".$row['id'];
$img = "<img src = 'images/delete.png'>";
echo "<a href=".$delurl.";
echo "onclick='return confirm('Are you sure you want to delete.')'>".$img."</a>";
Maybe the error is in double quotes or single quotes, Any help
Thanks in advance
change
echo "<a href=".$delurl.";
to
echo "<a href=\"".$delurl."\" ";
$delurl = "delete_dish.php?dish_id=".$row['id'];
$img = "<img src = 'images/delete.png'>";
$confirm_box <<<CONFIRM
<a href="$delurl"
onclick="return confirm('Are you sure you want to delete?')">$img</a>
CONFIRM;
// then elsewhere ...
echo $confirm_box
Always tend towards using the HEREDOC syntax to construct HTML/JS output, it will save you a lot of heartache. Just watch out for the major gotcha, DO NOT INDENT THE FIRST/LAST lines of the heredoc declaration.
EDIT The benefit being that you can mix single and double quotes as much as you like, you only have to worry about the JS quoting - PHP variables are interpolated without the quotes. You can further wrap curly quotes around your PHP variables like {$this} to make it easier to read, but also to delineate $this and {$this}tle.
I would us the following instead of escaping, this is more readable to me:
$delurl = "delete_dish.php?dish_id=".$row['id'];
$img = "<img src = 'images/delete.png'>";
?>
<?=$img?>
You can, may and should escape when handling stuff like this:
echo "<a href=\".$delurl.\"";
echo " onclick=\"return confirm('Are you sure you want to delete.')\">".$img."</a>";
lg,
flo

How to PHP echo when using multiple quotes

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;

Categories