javascript variable in php code - javascript

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

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.

Concatenation Unexpected Identifier error PHP

I'm trying to do some concatenation in Magento 1.x and am getting an "Unexpected Identifier" error, the following code is the snippet, and each of the PHP echos are formatted as:
$product->getPrice() - Integer - e.g: 45.00
$product->getName() - String - e.g: Product Name Here
var testVar = "12345::'" + echo $product->getPrice() + "'::'" + echo $product->Name() + "'::ProductID";
I can't figure out why it's not working, can anyone help please?
var testVar = "12345::'" <?php echo $product->getPrice() ?> "'::'" <?php echo $product->Name()?> "'::ProductID";
refer Concatenation php string to javascript string

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

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

Pass a variable from JavaScript to PHP

I'm trying to pass the variable from a JavaScript function - selected text - to the same page using php post method:
if (isset($_POST['u_name']))
{
echo $_POST['u_name'] . '</p>';
}
echo "<script type='text/javascript'>";
echo "var var1 = 0; var range = window.getSelection ();";
echo "function gst () { var range = window.getSelection (); alert (range.toString ()); var1 = range.toString ();}";
echo "document.write('<form method=\'post\'>');";
echo "document.write('<p>selected area:<br />');";
echo "document.write('<button onclick=\'gst ()\' type=\'submit\' name=\'u_name\' value = \'' + var1 + ' \' />Button</button>');";
echo "document.write('</form>');";
echo "alert (interesting);";
echo "</script>";
after pressing the button the selected page text is correct: it is checked with alert (range.toString ()) , however, the initial value of var1 variable - 0 is posted.
What could cause it and how one can pass the value, obtained from the javascript function through post method ?
Anton
That's because you set value attribute on the page load.
You can change it dynamically on button click. Replace one of your rows to:
echo "document.write('<button onclick=\"this.setAttribute(\'value\', var1); gst()\" type=\'submit\' name=\'u_name\' value = \'' + var1 + ' \' />Button</button>');";
Note this.setAttribute.
If you want to pass JavaScript variables to PHP, you'll have to use an Ajax request.
PHP is server sided, whereas JavaScript is client sided. This means that all PHP code is done before any JavaScript is even triggered. You can manipulate JavaScript with PHP, but if you want to manipulate PHP with JavaScript, use an Ajax call.

Categories