Expressing php code in Javascript - 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! :-)

Related

PHP modify fetched variable and return to frontend for JS

Im fetching Product Attributes from Woocommerce, and echo them out in a script tag as variable to use with javascript in frontend.
This might be a bad practice, feel free to enlighten me.
Example:
Product Attributes:
Total height: 43m
Total length: 55m
PHP queries "Total-height" as Attribute Name and "43m" as Attribute Value.
PHP replaces empty space with "-".
I can't define a javascript var with "-" in var name.
Example: var Total-height = "43m";
How could I fix this issue?
Here is my code.
Thanks in advance.
function product_attribute_dimensions(){
global $product;
foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) {
// Get the attribute label
$attribute_label_name = wc_attribute_label($taxonomy);
$value = $product->get_attribute($taxonomy);
if ($value) {
$label = get_taxonomy($taxonomy)->labels->singular_name;
$profile_one = $value;
echo '<script>' . $attribute_label_name . ' = "' . $value . '";
</script>';
}
}
try using window["variable_name"]
do this:
echo '<script>window["' . $attrname . '"]=' . $attrval
then in your js:
let this_var = window[attrname]
It seems like the clearest shortest way to do this.
As I understand the generated string in the variable "$attribute_label_name" is the problem? Take a look at https://www.php.net/manual/de/function.str-replace.php
With this native PHP function you can search for a character (eg."-") and replace with something else (eg. "_")
echo '<script>' . str_replace("-", "_", $attribute_label_name) . ' = "' . $value . '";
But as you said, this might not be the best approach. I personally would add this kind of information into a "data-X" HTML attribute in some HTML element and would extract this in my JS. Similar to this:
<div id="some_element" class="could be hidden" data-total-height="<?= $value ?>"></div>
You could Query something like this with jQuery $("#some_element").attr("data-total-height")
function product_attribute_dimensions() {
global $product;
$product_atrributes = array();
foreach ($product->get_attributes() as $taxonomy => $attribute_obj) {
// Get the attribute label
$attribute_label_name = wc_attribute_label($taxonomy);
$attribute_label_name = str_replace(' ', '_', $attribute_label_name);
$value = $product->get_attribute($taxonomy);
if ($value) {
$product_atrributes[$attribute_label_name] = $value;
}
}
echo '<script type="text/javascript">var product_atrributes = ' . json_encode($product_atrributes) . ';</script>';
}
Now you can use in JS like product_atrributes.Total_height.value
This way the redundant script tag also can be avoided.

placing php inside javascript

<script>
var strWidth = document.getElementById("mydiv").style.width;
var strHeight = document.getElementById("mydiv").style.height;
var link = "<?php if(isset($_GET["ggg"])) {
echo $_GET["ggg"].".php?width=800&height=460";
} else {
echo "page1.php?width=800&height=460";
}
?>";
</script>
this is my script, php inside javascript. how do i place this variable strWidth inside
php?width=800&height=460
so becomes some how like this
php?width=strWidth&height=460
EDIT 2
well, the only thing i am trying to do here to show variable value between those line is it a big deal ?
it might be done by separating like using concatenation or something ?
Add an input-field in PHP, hide it (if necessary) and read the value of this field with JS.
First of all if you want to use php values in javascript you need the script to be written in a php file. Suppose you do this then you can do this in this way:
<script>
var strWidth = document.getElementById("mydiv").style.width;
var strHeight = document.getElementById("mydiv").style.height;
var link='<?php echo (isset($_GET["ggg"]))?isset($_GET["ggg"]):''; ?>'; // this assigns the valueto link variable
if(link==''){
// your logic starts here
}else{
// your logic starts here
}
</script>
Add an input-field and assign a value to the hidden element and then get value through javascript.
It is not a good idea to combine PHP and Javascript.
Refer this about explanation on client-side vs server-side coding.
you can't really do that. but this works
<?php
echo "<script>\n";
echo "var strWidth = document.getElementById(\"mydiv\").style.width;\n";
echo "var strHeight = document.getElementById(\"mydiv\").style.height;\n";
if(isset($_GET["ggg"])) {
echo "var link =" . $_GET["ggg"] . ".php?width=800&height=460';\n";
}
else {
echo "var link ='page1.php?width=' + strWidth + '&height=' + strHeight + '';\n";
}
echo "</script>\n";
?>
the reference to ggg completely confuses the understanding of this process so really it should be taken out:
__ page1.php
<?php
if (!isset($_GET['foundWidth'])){
//stops double hit
echo "<script>\n";
echo "var strWidth = document.getElementById(\"mydiv\").style.width;\n";
echo "var strHeight = document.getElementById(\"mydiv\").style.height;\n";
echo "var link ='/page1.php?foundWidth=true&width=' + strWidth + '&height=' + strHeight + '';\n";
echo "window.location = link;"
echo "</script>\n";
}
elseif (isset($_GET['foundWidth']) && ($_GET['foundWidth']=='true')) {
if (isset($_GET['width']) && is_numeric($_GET['width'])){
//use your width here SERVER SIDE
// or
echo "<script> alert('Width is: '+ " . $_GET['width']) . "); </script>\n";
}
if (isset($_GET['height']) && is_numeric($_GET['height'])){
//use your height here SERVER SIDE
// or
echo "<script> alert('Height is: '+ " . $_GET['height']) . "); </script>\n";
}
}
?>
using this "trick" you can then write the PHP params into the javascript url with whatever get string you like, including triggering a reload of the page with the width as a param, so if you want to test if $_GET['width'] is set to a number you can insert it etc

Passing a string with double quotations as parameter from php to 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>';

javascript variable in php code

Hi guys I'm working with google charts.
I'm using PHP to capture the data i need from a database which is then stored into a incramental varible (month1 , month2, etc.)
Now i need to pass this to javascript when i was using just a set number of months this was fine as i used the code:
var month1="<?php echo $month1value; ?>";
I created a while loop that starts [i] at 1 and then increases to the number of months used.
I am new to javascript so assumed i would be able to do something like this:
var month[i] = "<?php echo $month" + i + "value; ?>";
however this doesn't work and i get:
Parse error: syntax error, unexpected '" + i + "' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ';'
Can anyone help?
you don't need save data in variable (month1 , month2, etc.).
you can you something like this:
echo "<script type='text/javascript'>";
while ($row = mysql_fetch_array($result)) {
echo "var month[i] = " . $row["month"] . ";";
}
echo "</script>";
I hope this code help you

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 :)

Categories