Use a php variable into javascript - javascript

class Map
{
public $Id;
public $longitudes;
public $latitudes;
public $lat_init;
public $lng_init;
public static function createMap($Id){
global $latitude, $longitude;
$dbh = Database::connect();
$query = "SELECT * FROM `cartes` WHERE Id=? ";
$sth = $dbh->prepare($query);
$sth->setFetchMode(PDO::FETCH_CLASS, 'Map');
$sth->execute(array($Id));
if ($sth->rowCount() === 0) return NULL;
$map=$sth->fetch();
$sth->closeCursor();
$lat=$map->latitudes;
$lng=$map->longitudes;
$latitude=unserialize($lat);
var_dump($latitude);
$longitude=unserialize($lng);
echo'<script type="text/javascript">'
,'var lat = json_encode($latitude);
var lng = json_encode($longitude);
draw(lat,lng);
'
,'</script>';
}
}
<?php
$dbh=Database::connect();
Map::createMap(6);
?>
When i excute this code, the following error appears: "$latitude is not defined". var_dump($latitude) is ok. I think the script doesn't recognize $latitude but i don't know why. Any help?
thanks

If you're encoding it into JSON, you'll need to wrap it in quotes correctly (you can't call functions inside strings):
echo '<script type="text/javascript">
var lat = '. json_encode($latitude). ';
var lng = '. json_encode($longitude). ';
draw(lat,lng);
</script>';

With PHP, single quote are for string literals and will use the name of the variable instead of its value. If you want interpolation (inserting a variable's value into the string), you need to use double quotes.
echo '<script type="text/javascript">',
"var lat = ". json_encode($latitude) .";
var lng = ". json_encode($longitude) .";
draw(lat,lng);",
'</script>';
Update: I somehow overlooked the part about json_encode being a PHP call... so the interpolation issue is a moot point, since you just need to concatenate the function's output into the string.

Functions aren't called inside quoted strings. You need to concatenate it:
echo '<script type="text/javascript">
var lat = ' . json_encode($latitude) . ';
var lng = ' . json_encode($longitude) . ';
draw(lat,lng);
';

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

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

Simple PHP array to Javascript array

I have an array in php lets call it:
$nums = array(10,25,52,32,35,23);
I want to send it to my javascript function like this:
var nums=[10,25,52,32,35,23];
How can i do this?
(My javascript file name is "nums.js")
Edit:
nums.js is a javascript code. It changes the values of table in the html. But the values only exist in php. So i have to send the values to javascript.
PHP >= 5.2
The json_encode function is for this purpose:
<?php echo 'var nums=' . json_encode(array(10,25,52,32,35,23)) . ';'; ?>
Docs: http://php.net/json_encode
PHP < 5.2
If you can't use json_encode, take a look at this post for a way to define an equivalent.
As long as your javascript file is being parsed by PHP before being sent to the client, then this should work:
<?php echo "var nums=[" . implode(',', $nums) . "];"; ?>
Just json_encode() the array and then output it as an array literal in javascript.
<?php
$nums = array(10,25,52,32,35,23);
$nums_json = json_encode($nums);
?>
<script type="text/javascript">
var nums = <?php echo $nums_json; ?>;
</script>
you can also use json_encode() but only possible from php 5.2
see more: http://us3.php.net/manual/fr/function.json-encode.php
or you can use this function:
function php2js ($var) {
    if (is_array($var)) {
        $res = "[";
        $array = array();
        foreach ($var as $a_var) {
            $array[] = php2js($a_var);
        }
        return "[" . join(",", $array) . "]";
    }
    elseif (is_bool($var)) {
        return $var ? "true" : "false";
    }
    elseif (is_int($var) || is_integer($var) || is_double($var) || is_float($var)) {
        return $var;
    }
    elseif (is_string($var)) {
        return "\"" . addslashes(stripslashes($var)) . "\"";
    }
    return FALSE;
}

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