placing php inside javascript - 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

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.

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

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.

Send numbers from php to js in separated files

How to send variables from php to js in separated files. Can I make this without ajax or I need ajax for this. If I need ajax how to make with ajax.
test.php
<?php
$a = 5;
$b = 10;
?>
test.js
var sum =<?php echo $a?> + <?php echo $b?>
document.write(sum);
You can get javascript to know about some data you want to transfer from PHP to javascript quite easily.
But you have to make the javascript valid i.e. I think you were missing the ; at the end of your javascript calculation. It gets a bit hard to see the wood for the tree's sometimes, making sure there is a javascript ; and a PHP ;
<?php
$a = 5;
$b = 10;
echo '<script type="text/javascript">';
echo 'var aFromPhp = ' . $a . ';';
echo 'var bFromPhp = ' . $b . ';';
echo 'var sum = aFromPhp + bFromPhp;';
// or your line
echo 'var sum = ' . $a + $b . ';';
echo '</script>';
NOTE: Doing it this way does tend to mess up the Global scope in javascript with lots of variables and it not really recommended, but it works.

PHP: pass variable to javascript method [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
What I have:
Try to pass variable to javascript method in such way:
$name = (string) $form->attributes()->name;
$show = 'show("'.$name.'")';
echo '<input type="radio" onclick="'.$show.'">'.$form['description'].'<br />';
print_r($show); // show("feedback")
...
<script>
function show(name) {
//DEBUG HERE!
...
}
</script>
What a problem:
In browser's debugger I can see that into show method I've passed the whole form (means that argument name equals to the whole form).
Question:
Why does it happen? How to pass to js-method only form's name?
I think you are just missing some quotes around it:
echo '... onclick="show(\"'.$name.'\")> ...';
Note the \" I put around $name. In your code, if $name = "Foo", it would write show(Foo) instead of show("Foo").
I think you are not escaping the string properly to be used by the JS function. Try escaping the strings like this:
$name = 'feedback';
$description = 'description';
//like this
echo '<input type="radio" onclick="show('. "'" . $name . "'" . ')">' . $description . '<br/>';
// or like this
echo "<input type=\"radio\" onclick=\"show(' . $name . ')\">" . $description . "<br/>";
<script>
function show(name) {
alert(name);
}
</script>
I hope this helps.

Categories