Passing a string with double quotations as parameter from php to javascript - javascript

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

Related

Set innerhtml of a div echoed by php

I created a div element using php echo
*//some html code*
*<?php echo "<div id = "randomDiv"></div>" ?>
<script>
document.getElementById("randomDiv").innerHTML = "Hey";
</script>*
but this does not manipulate the innerHTML of the div. Any ideas how to resolve this?
Double quote for div id makes it invalid. Try changing the quote to single quote:
<?php echo "<div id='randomDiv'></div>"; ?>
<script>
document.getElementById("randomDiv").innerHTML = "Hey";
</script>

Expressing php code in Javascript

I am trying to insert html code through a php variable in javascript. I am getting the following error below. Please can someone advise?
Error Message: "Unexpected Identifier 'Inactive'" ($option has values 'Inactive'/ 'Active')
PHP
$tr_active_Options = '';
$sql1 = "SELECT status FROM tr_active";
$result = $mysqli -> query($sql1);
while($row = $result -> fetch_assoc()){
$option = $row['status'];
$option = '<div class="dpOtions" onclick="track.addChosenOption(\''.$option.'\', \'act_ui\')">'.$option.'</div>';
$tr_active_Options .= $option;
}
$tr_active = '<div class="drpClass"><div class="dropOptionsDiv" id="actList_ui">'.$tr_active_Options.'</div></div>';
JAVASCRIPT
document.getElementById('anchor').innerHTML = '<div id="editWrap"><?php echo $tr_active; ?></div>';
The ' in your string are terminating the JavaScript string you've started with '.
You can safely have PHP generate a string for use in JavaScript using json_encode, like so:
document.getElementById('anchor').innerHTML =
'<div id="editWrap">' +
<?php echo json_encode($tr_active); ?> +
'</div>';
Note how the JavaScript string ends, then we use + to join it with the one that PHP will output (json_encode will handle the strings), then we + it with another JavaScript string after it. What the browser will see will look like this:
document.getElementById('anchor').innerHTML =
'<div id="editWrap">' +
"contents of $tr_active here" +
'</div>';
...which is valid.
That said: Using PHP to generate HTML with embedded JavaScript inside attributes is asking for a world of hurt. Separate those concerns! :-)

Add new selection with options from database

I have a function to add a new selection using button in the table with ID="maTable"
<button type="button" onclick ="addNew()"> Add More Agent</button>
Using JS :
function Addnew(){
var table=document.getElementById("maTable");
var row=table.insertRow([table.rows.length]-1);
var len=(table.rows.length);
var newid="agentID"+len;
var newida="agentGroup"+len;
var cell1=row.insertCell;
var cell2=row.insertCell;
var cell3=row.insertCell;
var new_optionAgent =
"<select class=\"opsi\"id="'+newida+'">"
+"<option selected=\"selected\"disabled=\"disabled\">Agent<\/option>"
+"<option value=\"agentA\">Agent A<\/option>"
+"<option value=\"agentB\">Agent B<\/option>"
+"<option value=\"agentC\">Agent C<\/option>"
+"<option value=\"agentD\">Agent D<\/option>"
+"<\/select>"
cell1.innerHTML="Choose Agent" +" "+len;
cell2.innerHTML=":";
cell3.innerHTML= new_optionAgent;
}
With this I can get a button that will generate a new selection with 4 options (it works). But now come the problem when I want to change the option with the list from database. Im using php and postgres database. I made the code for the one that isn't generated from the "AddNew" button yet :
<?php
$que=pg_query("SELECT agentname FROM Agent");
echo "<select name=\"agentname1\"class=\"opsi\" id=\"agentGroup1\" required>";
echo "<option value=\"\" selected=\"selected\"disabled='disabled'>Agent</option>";
While($row=pg_fetch_array($que))
{
echo '<option value="'.$row['agentname'].'"> '.$row['agentname'].'</option>';
}
echo "</select>";
?>
Now I want to make the "AddNew" button that generate a selection with option list from database. I have combined the php code with variable "new_optionAgent" by adding "\" to some symbols. but it doesnt work.
I combine like this
var new_optionAgent =
'<\?php
\$que=pg_query(\"SELECT agentname FROM Agent\")\;
echo \'<select name=\\\"agentname1\\\"class=\\\"opsi\\\" id=\\\"agentGroup1\\\" required>\'\;
echo \'<option value=\\\"\\\" selected=\\\"selected\\\"disabled=\\\'disabled\\\'>Agent</option>\'\;
While(\$row=pg_fetch_array(\$que))
{
echo \'<option value=\"\'\.$row[\'agentname\']\.\'\"> \'\.$row[\'agentname\']\.\'</option>\'\;
}
echo \"<\/select>\"\;
\?>'
this combination is seems very wrong, Any help? Thank you
This is not working because the escaped backslashes is used by PHP for escaping the double quotes. So you will need to add another set of backslases and escape those, or use a single quote string in PHP:
<?php
$que=pg_query("SELECT agentname FROM Agent");
echo '<select name=\"agentname1\"class=\"opsi\" id=\"agentGroup1\" required>';
echo '<option value=\"\" selected=\"selected\"disabled=\'disabled\'>Agent</option>';
While($row=pg_fetch_array($que))
{
echo '<option value="'.$row['agentname'].'"> '.$row['agentname'].'</option>';
}
echo "</select>";
?>
Edit
You can't inline PHP inside a Javascript variable like that. Try this:
<?php
$que=pg_query("SELECT agentname FROM Agent");
$whateverYouWannaCallThisString = '';
$whateverYouWannaCallThisString .= '<select name=\"agentname1\"class=\"opsi\" id=\"agentGroup1\" required>';
$whateverYouWannaCallThisString .= '<option value=\"\" selected=\"selected\"disabled=\'disabled\'>Agent</option>';
While($row=pg_fetch_array($que))
{
$whateverYouWannaCallThisString .= '<option value="'.$row['agentname'].'"> '.$row['agentname'].'</option>';
}
$whateverYouWannaCallThisString .= "</select>";
?>
<script type="text/javascript">
var new_optionAgent = "<?php echo $whateverYouWannaCallThisString; ?>";
</script>
More info on escaping
The whole reason you are escaping characters is because you are using characters that surrounds the string itself. E.g: If you are defining a string with double quotes " like this: var myString = "Yolo" and you want to have double quotes " in that string like this: var myString = "Dude, wheres "my" car" then you need to escape the double quotes " thats inside that string like this: var myString = "Dude, wheres \"my\" car".
The same applies to PHP
//Edit :
I edited the variable :
var new_optionAgent =
<?php echo json_encode($whateverYouWannaCallThisString); ?>;
and it works :)

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!

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.
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>

Categories