n3ISe
n3ISe

Reputation: 159

quotes in onclick event

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.

Upvotes: 0

Views: 141

Answers (5)

lyhong
lyhong

Reputation: 947

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>

Upvotes: -1

rajesh kakawat
rajesh kakawat

Reputation: 10896

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)

Upvotes: 1

Nis
Nis

Reputation: 1477

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>

Upvotes: 0

Parixit
Parixit

Reputation: 3855

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
}

Upvotes: 0

Entoarox
Entoarox

Reputation: 703

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

Upvotes: 4

Related Questions