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!
Related
I've been trying to figure this thing out and I don't know what I'm doing wrong or maybe I'm missing something.
I'm trying to pass a string which contains double quotes that I retrieved from my database to be displayed in a textarea.
Situation sample looks like this:
<?php
$content = '<div align="center"><b>This is a sample content.</b></div>';
echo '<textarea id="myTextArea"></textarea>';
echo '<button onclick="myFunction('.$content.')">Click me</button>';
?>
<script>
function myFunction(content){
document.getElementById("myTextArea").innerHTML = content;
}
</script>
Expected results should be that myTextArea should contain the text, but the result shows:
Output
Your help is greatly appreciated.
You should quote your output using htmlspecialchars(), such that it reads:
<?php
$content = "<div align=\"center\"><b>This is a sample content.</b></div>";
echo '<textarea id="myTextArea"></textarea>';
echo '<button onclick="myFunction(\''.htmlspecialchars($content).'\')">Click me</button>';
?>
<script>
function myFunction(content){
document.getElementById("myTextArea").innerHTML = content;
}
</script>
You need to escape your quotes inside the string:
$content = "<div align=\"center\"><b>This is a sample content.</b></div>";
You could also use apostrophes in this case, like
$content = "<div align='center'><b>This is a sample content.</b></div>";
or
$content = '<div align="center"><b>This is a sample content.</b></div>';
EDIT:
Also, make sure you use content as a string:
echo '<button onclick="myFunction(\''.$content.'\')">Click me</button>';
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>";
}
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"}")>
I have here my href link being echoed:
echo "<td><a href='../php/borrowersname.php?acc_number=".$row['acc_number']."'>".$row['title']."</a></td>";
And I have here a sample on how to create a Pop-Up:
Test
How to combine this to my href link above being echoed with the "javascript ... ..." enclosed by ("" && '')?
Thanks for another new learning.
You can escape the ""
<?php
echo "Test";
?>
In the 'borrowersname.php' page, you can get the value of 'acc_number' like this:
<?php
$value = $_GET['acc_number'];
//do something with $value;
?>
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>