PHP: pass variable to javascript method [duplicate] - javascript

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.

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.

How do I post a variable from jQuery to a PHP file? [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 4 years ago.
I realize there have been other answers to similar questions before, however I'm trying to make a collection of links unique in a table and can't seem to get the id of the tag to post to a php page.
See below:
echo("<p>To reserve a book, click the Book Title.</p>");
echo "<table class='formfield' border='1'>
<tr>
<th>Book ID</th>
<th>ISBN</th>
<th>Book Title</th>
<th>Author</th>
<th>Edition</th>
<th>Year</th>
<th>Category</th>
<th>Reserved</th>
</tr>";
$lnkCount = 0;
while($row = mysqli_fetch_array($sql)) {
$lnkCount++;
echo "<tr>";
echo "<td>" . $row['bookID'] . "</td>";
echo "<td>" . $row['ISBN'] . "</td>";
echo "<td><a class='anchor' id='$lnkCount' href='reservation.php'>" . $row['BookTitle'] . "</a></td>";
echo "<td>" . $row['Author'] . "</td>";
echo "<td>" . $row['Edition'] . "</td>";
echo "<td>" . $row['Year'] . "</td>";
echo "<td>" . $row['CategoryDept'] . "</td>";
echo "<td>" . ($row['Reserved'] ? 'Yes' : 'No') . "</td>";
/*echo "<td><input id='$lnkCount' type='button' value='Reserve Now' onClick='post();'></td>";*/ // display yes/no rather than boolean equivalent...
}
echo "</table>";
Then my jQuery:
<script lang="JavaScript" type="text/javascript">
$(".anchor").click(function() {
var clkID = $(this).attr("id");
alert(clkID);
$.post('reservation.php'), {clkID:postid}, function(){/*do something*/};
});
</script>
And finally my php page, which isn't really relevant but I'll post for clarity in my question.
$id = $_POST['postid'];
echo("<p>Value detected was: $id</p>"); // this is just to test...
Now when I click on one of the links, the page alerts with the correct id of the link I clicked. But then when it connects to the php page (reservations.php) it gives me the following error:
Notice: Undefined index: postid in C:\xampp\htdocs\webDevProj\reservation.php on line 41
Value detected was:
As I'm sure >=1 of you will know I'm not very experienced with jQuery - so if you understand my problem and think there's a much easier way to do it I would really appreciate your input!
p.s. it's for a college assignment :)
EDIT #1 --
Don't see how this question has any relevance to the one reported as answered. It involves jQuery .post methods. The "solution" provided gives various definitions to what "undefined index" means in regards to php but does still not have any significance on my question.
EDIT #2 --
So I changed the variable and the key around in my JS code without any change. I was hopeful for that split second lol - guess I'll keep looking...
Add this changes to your PHP script
From:
$id = $_POST['postid'];
To:
$id = $_POST['clkID'];
Or edit JS request:
$.post('reservation.php'), {postid:clkID}, function(){/*do something*/};
You're looking for the wrong key in $_POST. In your AJAX call you set the parameter to have the name clkId. So:
$id = $_POST['postid'];
should be
$id = $_POST['clkId'];
In your javascript you are storing the retrieved value in clkID, so your jQuery needs to be
$.post('reservation.php'), {postid:clkID}, function(){/*do something*/};
which will pass that variable to PHP with the name postid.
$.post( "reservation.php", { postid: clkID })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
And in your php page :
$id = $_POST['postid'];
return $id; // just to test to see if you get this in data of done function
{ postid: clkID } - This means name of variable should comes first and then you can send value of your variable.
https://api.jquery.com/jquery.post/ // for your reference
Problem with your variables name.
Please write like below code:
In JS:
var clkID = $(this).attr("id");
$.post('reservation.php'), {postid:clkID}, function(){/*do something*/};
Because your data are stored in clkID.
Ant then call in controller.
$id = $_POST['postid'];
If you changed variable in PHP script then you can get empty data because there is no data defined in postid in javascript.

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

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

Use a php variable into 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);
';

Categories