quotes in onclick event - javascript

I had an onclick event as below.
<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')"></div>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
the function works fine with the name like Mary, Chris and etc.
However, if the student name contains a ', e.g. Cheng'li, the function won't work.
I need help to fix this. How can I make the function works by 'escaping' the quote mark in name?
Thanks.

You need to add a call to htmlentities around the data you wish to echo.
Not doing so exposes your code to XSS attacks.

use PHP function addslashes
<?php
$str = "Is your name O'reilly?";
// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>
IN your case
<?php echo addslashes($student_name);?>
REFERENCE
http://www.php.net/addslashes
Note: If your code contain html tag than use htmlentities (Entoarox Answer)

you can either use escape()
<div onclick="display_function(escape('<?php echo $user_id;?>'),escape('<?php echo $student_id;?>'),escape('<?php echo $student_name;?>'))"></div>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}

That is because you are passing the values in function in single quotes. When name will have a single quote, this will cause error.
try double quotes like
<div onclick="display_function(\"<?php echo $user_id;?>\",\"<?php echo $student_id;?>\",\"<?php echo $student_name;?>\")"></div>

Just add \ before ' to tell your script that it is a string. I hope it helps
<?php
$user_id = 1;
$student_id = 1;
$student_name = "Cheng\'li";
?>
<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')">Click</div>
<script>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
</script>
If you cannot put \ directly in String, you need to use [addslashes][1]
<script>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+addslashes(student_name)); //<-- testing only. I have my own code here
}
</script>

Related

Pass PHP variable to javascript including quotes and javascript

This question has been asked a few times, and the answer seems to be to use json_encode but this is not working as my string contains a few more things than quotes.
This is the PHP string:
<img src="test.jpg" :class="{ 'add-class': comment == 1, 'another-class': comment == 2 }" x-on:click="submit()">
The :class and x-on: are AlpineJS attributes in case you were wondering (check it out, it's really cool!).
This PHP string is dynamically generated and I would like to pass it to a javascript variable, shown here as jsVariable:
<script>
function test() {
return {
jsVariable: ,
anotherVariable: true,
}
}
</script>
Update
If I use jsVariable: <?php echo json_encode($php_variable); ?>, I get SyntaxError: Unexpected token '&' on that line.
If I use jsVariable: '<?php echo json_encode($php_variable); ?>', (added single quotes) then the variable is parsed as a string and not as HTML.
Use json_encode():
<script>
function test() {
return {
jsVariable: <?php echo json_encode($php_variable); ?>,
anotherVariable: true,
}
}
</script>
If you just use ASCII coding, you may give base64 encoding a try.
PHP encode the string into base64, and Javascript to decode, like this:
<script>
function test(){
var str = '<?php echo base64_encode($str);?>';
return {
jsVariable: atob(str),
anotherVariable: true
}
}
alert(test().jsVariable)
</script>
Hope this helps.

Run JS Function when PHP

I got a Javascript function called edit like this :
function edit(id){
window.opener.location.href='../../../index.php?mi=<?php echo $mi1?>&id='+id;
//window.close();
}
It already work if i use a href so i need to click the link
<a href="javascript:void(0);" onClick="edit('<?php echo $_POST["id"]?>');">
<?php echo $_POST["id"]?>
</a>
Then i want to run the function when i save / update data
if(isset($_POST["save"])){
...
...
echo " <script>$(document).ready(function(){edit(".$_POST["id"].")};</script>";
}
But it didn't work, did i do something wrong ?
try this
$id = $_POST["id"];
echo "<script>$(document).ready(function(){edit(".$id.")});</script>";
you have used double quotation like this edit(".$_POST["id"].").
also closing ) is missing.
Try This Code
if(isset($_POST["save"])){
echo "<script>$(document).ready(function(){edit(".$_POST['id'].")};</script>";
}

How to create alert function in php?

i want insert user in db mysql, i have a controller php, im validate if user exist in db through a function, then if or not exist i want show alert function an redirect to php page, for that im using:
<?php
if(dao::existUser($user)) {
echo "<script type=\"text/javascript\">\n";
echo "alert('user exist!');\n";
echo "window.location = ('../insertUser.php');\n";
echo "</script>";
}
this function works!! but
i want to encapsulate the function in a method to later call it
example:
<?php
class Utils {
static function responseText($message, $url) {
echo "<script type=\"text/javascript\">\n";
echo "alert('"+$message+"');\n";
echo "window.location = ('"+$url+"');\n";
echo "</script>";
}
}
then, in my controller:
<?php
if(dao::existUser($user)) {
Utils::responseText("user exist",'../insertUser.php');
}
but not work, and after call responseText, my page goes blank
I don't know what is wrong ( likely a quoting issue ), but I would suggest using a HEREDOC style for this and return the text not output the HTML from the class by itself. Latter it could be hard to track where this output is coming from by looking just in the class that calls it. By doing echo Utills::.. you'll be able to easily see it's outputting something, whiteout having to look into what the class does.
So like this.
<?php
class Utils {
static function responseText($message, $url) {
return <<<HTML
<script type="text/javascript">
alert('$message');
window.location = '$url';
</script>
HTML; //nothing can go here no space ( before or after ) and not even this comment, nothing but HTML; litterally
}
}
echo Utils::responseText("user exist",'../insertUser.php');
HEREDOCs are a way of doing a text block without using any quotes, beware of the note i put in comments... In this case it makes the Javascript string so much more simple when you don't have to manage quote usage.
Another suggestion for this class if it is to be a collection of static methods, you can make it where it can't be instantiated ( created using new class() ) Like this
<?php
class Utils {
private function __construct(){} //no instantion
private function __clone(){} //no cloning
This way you don't accidentally do $U = new Utils(); $U->responseText(..) It's a little thing but it will insure all the methods of this class stay static. It's just a design thing I like to do, on singletons and static classes
UPDATE your issue is you are using the + to concat in PHP where you should be using the . The + is good for Javascript not so much for PHP
And the way you have it with " double quotes concat is unnecessary, instead of
echo "alert('"+$message+"');\n";
Try
echo "alert('$message');\n";
If i understand you properly bind javascript to php.
<?php
$script = '<script type="text/javascript">';
$script .= 'function showAlert(){';
$script .= 'alert("Hello World.");';
$script .= '}';
$script .= '</script>';
echo $script;
?>
Than after page has loaded you can call it !
<script type="text/javascript">
window.onload = function () {
showAlert();
}
</script>

phpcoding special characters

When I load a php page, i put within a javascript function, a name. The problem comes when this string has special chars like '.
Here I paste the code of a click event:
showSocialShare(event, '<?php echo $object->slug; ?>', '<?php echo htmlspecialchars($object->title); ?>', '<?php echo $object->image; ?>')
I thought that the function htmlspecialchars code somehow the string but the result is:
showSocialShare(event, '4049269', 'collection-'Noun'', '/img/Original.jpg')
As can be seen, at the second parameter, the name contains characters like ' and arises an error.
How can I avoid this?
Never output text from PHP directly into a Javascript context. As you're finding out, it's VERY easy to generate JS syntax errors.
Always use json_encode: e.g. given this
<?php $foo = 'bar'; ?>
<script>
var badly_broken = <?php echo $foo ?>;
var working_fine = <?php echo json_encode($foo); ?>;
</script>
You'll end up with
<script>
var badly_broken = bar; // oops - undefined variable "bar"
var working_fine = "bar";
</script>
And note that if you're outputting JS into an HTML attribute, you not only have to generate valid Javascript, you have to output valid HTML AS WELL:
<?php $foo = array('bar' => 'baz'); ?>
<a onclick="brokenCall(<?echo json_encode($foo) ?>)">
<a onclick="workinCall(<? echo htmlspecialchars(json_encode($foo)) ?>)">
produces:
<a onclick="brokenCall({"bar":"baz"})">
^--start attribute
^--end attribute - ruhroh
<a onclick="workingCall({"bar":"baz"}")>

store Javascript code in PHP variable?

I would like to store JavaScript code in a PHP variable, in order to inject it multiple times into my main code:
<?php
$PASSME = <<<PASSME
alert("hello world");
PASSME;
echo "<a onclick=$PASSME >Click here</a>";
?>
In Google Chrome I can read this source code:
<a onclick="alert("hello" world");>Click here</a>
So I noticed this:
"hello" world" should be "hello world"
What am I doing wrong?
NB: I am actually working on a more complex project. I tried to make an example in order to understand how to correctly do it.
As I commented you used double quoetes in double quotes, use single quotes instead:
<?php
$PASSME = <<<PASSME
alert('hello world');
PASSME;
echo "<a onclick=\"$PASSME\" >Click here</a>";
?>
This will result in correct code:
<a onclick="alert('hello world');">Click here</a>
When having a lot of code, just pass variables from php to js, ie:
<?php
$PASSME = <<<PASSME
var message = 'hello world'
PASSME;
?>
<script>
<?= $PASSME; ?>
</script>
<?
echo "<a onclick=\"alert(message)\">Click here</a>";
?>
Use following (You missed Quotes around variable)
<?php
$PASSME = <<<PASSME
alert("hello world");
PASSME;
echo "<a onclick='".$PASSME."' >Click here</a>";
?>
The problem is that your attribute value contains space characters and is not delimited with quote characters.
<?php
$html_safe_passme = htmlspecialchars($PASSME, ENT_QUOTES);
?>
<a onclick="<?php echo $html_safe_passme; ?>">Click here</a>
You need to escape the " to " in the HTML attribute value. You also need to delimit the attribute value with double-quotes (which mustn't be encoded) because it contains spaces, like so:
(Also, personally I wouldn't use PHP's <<< for strings)
$passme = "alert("hello world");";
echo "<a onclick=\"$passme\">click here</a>";
Try it like this, with single quotes:
alert('hello world');
<?php
$PASSME = "alert('hello world');";
echo "<a onclick=". $PASSME . " >Click here</a>";
?>
try to add to change space in your code. and DONE!

Categories