Send numbers from php to js in separated files - javascript

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.

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

Inserting value in a JavaScript variable from php code

I am trying to test the following code for inserting the value from PHP code to my javascript variable x
tested the PHP code, and it's giving the correct output but the alert box in the javascript shows this -
date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000"; $query = mysql_query($myquery); if ( ! $myquery ) { echo mysql_error(); die; } $data = array(); for ($x = 0; $x < mysql_num_rows($query); $x++) { $data[] = mysql_fetch_assoc($query); } //echo json_encode($data); echo ''; mysql_close($server); ?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Testing </title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
<body>
<?php
$username='user';
$password='pass';
$host='xx.xx.xx.xx';
$database='abc';
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = 'select code a,sum(fee) b from xyz where date > date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000';
$query = mysql_query($myquery);
if ( ! $myquery ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
//echo json_encode($data);
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
mysql_close($server);
?>
<script type="text/javascript">
function test(){
var x = document.getElementById("myPhpValue").value;
alert(x);
}
test();
</script>
</body>
</html>
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
Then:
var x = document.getElementById("myPhpValue").value;
you need to insert id="myPhpValue", because you used the "getElementById";
Add ID attribute in the html line
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
replace the above line by
echo '<input type="hidden" name="myPhpValue" id ="myPhpValue" value="'. json_encode($data) . '">';
You are inserting a value into html, not javascript code.
Do it like that:
<script type="text/javascript">
function test(){
var x = <?php echo json_encode($data); ?>;
alert(x);
}
test();
</script>
Server configuration problems
If You are getting php code on client-side (view-source to confirm), then the PHP engine is not working on the server.
You should check that php is properly installed on the server and is set as a handler for php files in your web server.
This depends on your web server and operating system.
Code problems
Problem #1: your output (echo) is creating an HTML element, not javascript. Hence you should escape the content for HTML - use htmlspecialchars instead of json_encode
Problem #2: you access the element with javascript document.getElementById but your actual element does not have an ID. Hence need to add the id attribute to your html input element.
Solution:
Stage 1: php outputs html - use htmlspecialchars and add id attribute
echo '<input type="hidden" name="myPhpValue" id="myPhpValue" value="'. htmlspecialchars($data) . '">';
Stage 2: javascript accesses html element (this is taken as-is from your code).
var x = document.getElementById("myPhpValue").value;
Side-note
You're using a deprecated mysql extension and should switch to PDO or mysqli instead.
There are numerous discussions both on SO and external resources on the matter.
Just a few:
Choosing an API - PHP manual
What is the difference between MySQL, MySQLi and PDO?
mysqli or PDO - what are the pros and cons?

Array of Javascript in PHP

I was trying to get datas from the database and put them into the array in Javascript but Javascript is not working in PHP command area.
Here is the whole PHP codes;
<?php
mysql_connect("mysql.metropolia.fi","localhost","") or die("ERROR!!");
mysql_select_db("localhost") or die("COULDN'T FIND IT!!") or die("COULDN'T FIND DB");
$sql = mysql_query("SELECT * FROM METEKSAN_HABER_CUBUGU");
$haber = 'haber';
$list = array();
$i=0;
while($rows = mysql_fetch_assoc($sql)){
$list[] = $rows[$haber];
$i++;
}
echo $i;
echo '<script type="text/javascript">
var yazi=new Array();';
echo $i;
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']="'.$list[$k].'';
}
echo '</script>';
?>
But when it comes to;
echo '<script type="text/javascript">
var yazi=new Array();';
this command line, the problem begins. Though I write 'echo $i;' after that command, I get nothing on the screen but I get the result if I write before that command. So, it means that everything works well before that command. What you think about the problem ? Why can't I starting the Javascript command ? Am I writing something wrong ?
Please give me a hand.
Thanks.
UPDATE;
I opened the web source and yeah it exactly seems there is a problem. So, I think it's better to ask that how can I write
<script type="text/javascript">
/*Example message arrays for the two demo scrollers*/
var yazi=new Array()
yazi[0]='METEKSAN Savunma, Yeni Dönemin Örnek Oyuncusu Olmaya Hazır'
yazi[1]='METEKSAN Savunma Bloomberg TVde'
</script>
this Javascript code in PHP ??
You can see my output at http://users.metropolia.fi/~buraku/Meteksan/index.php
try something like this
while($rows = mysql_fetch_assoc($sql)){
$list[] = ''.$rows[$haber].'';
}
$js_array = json_encode($list);
echo "<script>var yazi = ". $js_array . ";</script>";
It seems you are executing it currently in your browser? Then you should find your second output when opening page source, because your browser tries to executes the output as JS code. If you execute it on cli, everything should work as expected.
EDIT based on your comment:
Bullshit i wrote before, obviously. Viewing line 122 of your current html shows me a problem with your quotation marks. try the following:
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']=\''.$list[$k].'\';';
}
In the end you should try to avoid using this kind of js rendering at all. The json_encode proposal of jeremy is the correct way to go.
You may have much more compact code:
....
$list = array()
while($rows = mysql_fetch_assoc($sql)) {
$list[] = $rows[$haber];
}
echo '<script type="text/javascript">' . "\n";
echo 'var yazi=';
echo json_encode($list,JSON_HEX_APOS | JSON_HEX_QUOT);
echo ";\n";
echo '</script>' . "\n";
What is this doing:
There's no need to count the added elements in $i, count($array) will give you the cutrrent number.. But it's not needed anyway.
Put some newlines behind the echo, better readable source
json_encode will format an JSON array from your php array, which can be directly used as source code.

Execute Javascript through PHP

I'm using this PHP code to write a HTML table, but it takes time to load. I was thinking it would be a good idea to let JavaScript do the job, but the problem is that $width and $height are dynamic and is defined on the server-side. How do I get around that?
echo "<table>";
for ($y = 0; $y < $height; $y++) {
echo "<tr>";
for ($x = 0; $x < $width; $x++) {
echo '<td x="' . $x . ' y="' . $y . ' id="' . $x . '-' . $y . '"></td>'; //coordinates to be used for cropping later
}
echo '</tr>';
}
echo '</table>';
I'm unsure if this is best practice, but you can echo from PHP directly into Javascript. For example:
<script>
var width = <?php echo $width; ?>;
var height = <?php echo $height; ?>;
//now build table here using the Javascript width and height variables
</script>
Put PHP variables in javascript
<script>
var height = <?php echo $height ?>;
</script>
If no paramount forms are intented to exist in your page, you can store them in hidden HTML tags as hidden inputs, like this:
echo ="<form action ='#' name='form'>
<input type='hidden' name='v_height' id='v_height' value='".$height."'>
<input type='hidden' name='v_width' id='v_width' value='".$width."'>
</form>";
And then in Javascript get those variables and iterate with them.
jHeight = parseInt(document.form.v_height.value);
And so with the width.

Categories