PHP variable in JavaScript is not getting updated - javascript

I'm trying to pass a PHP variable (number) to JavaScript. It kind of works but as soon as the number changes, it's not getting updated. My code:
$totalamount = $woocommerce->cart->get_total();
$totalamount = preg_replace("/[^0-9\.]/", "", $totalamount);
$totalamount = number_format($totalamount, 2, '.', '');
var_dump($totalamount);
?>
<script type="text/javascript">
var Amount = "<?php echo $totalamount; ?>"
In the var_dump($totalamount); the number get's updated every time. In JavaScript it gives 0 after a change.
What is the proper way to pass a variable to JavaScript so it gets updated?

PHP is a server side language which means it is only executed at the time the page is loading, and the code will not be re-run unless you refresh the page.
To get around this you can retrive the total using an AJAX call which would get the total in the background and then update the page.
To get started with Ajax here is a good tutorial: Ajax

Related

How do i make a function that will repeat itself and keep on extracting new values from the database? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
So, I need to develop a function that will invoke when the page is loaded at the start and will extract the value from the database and display the same. The value of cod and bod will keep on updating in the database so what I need is to display that updated value onto a page without reloading or refreshing. Thank you.
code:
<?php
include("dbconfig.db");
?>
<script>
function update_data()
{
</script>
<?php
$execute_query = "SELECT cod,bod,tss FROM front_end_data WHERE
slave_id=1";
$output=mysqli_query($conn,$execute_query);
$result_data = mysqli_fetch_assoc($output);
$cod_data = $result_data['cod'];
$bod_data = $result_data['bod'];
$tss_data = $result_data['tss'];
?>
<script>
setTimeout(update_data, 5000);
}
window.onload = function()
{
update_data();
};
</script>
<html>
<head>
<title>
test
</title>
</head>
<body>
<h2>COD DATA: <?php $cod_data ?></h2>
<h2>BOD DATA: <?php $bod_data ?></h2>
<h2>TSS DATA: <?php $tss_data ?></h2>
</body>
</html>
You need Javascript for this. Once the page is loaded, the PHP script has finished executing, so you need to rely on JS for further page interactions after loading.
Your code example is mixing server-side processing with client-side processing. To separate those concerns out, make a single PHP page that serves up the data. Then make a HTML page with javascript that fetches the data from the PHP output. You might like to look at https://www.w3schools.com/php/php_ajax_database.asp as a starting point.
You need to use ajax for this functionality, You can trigger you ajax call with in a timeframe. But it'll make unnecessory calls to server every time. Instead you can use pusher, You can trigger an event whenever a DB value get updated.
Your Code is mixing Server Side Code with Client Side Code resulting into code vulnerabilities. Instead try doing ajax, and do setTimeout Function. What it does is it will call at every X timestamp and fire AJAX to server side and bring up the data.
Here is the nice example to do that:
https://guide.freecodecamp.org/jquery/jquery-ajax-post-method/

Print a javascript variable in php

I am selecting a payment method and making an AJAX call But I am not able to print the paymentOption parameter
I tried storing it in a cookie
if(paymentOption == "default_cod"){
processOrderWithCOD();
optionPayment = Cash;
}
document.cookie = "$payment_option = $this.optionPayment";
PHP:
<?php
$paymentOptionDisplay = $_COOKIE['payment_option'];
echo $paymentOptionDisplay ?>
I am just trying to print paymentOption but later on its value is changed so need to save it and print
You have to remember that if JS and PHP live in the same document, the PHP will be executed first (at the server) and the JS will be executed second (at the browser)--and the two will NEVER interact (excepting where you output JS with PHP, which is not really an interaction between the two engines).
In other words, if the two live in the same document and no extra interaction with the server is performed, JS can NOT cause any effect in PHP. Furthermore, PHP is limited in its effect on JS to the simple ability to output some JS or something in context of JS.
$paymentOptionDisplay = $_COOKIE['payment_option'];
Cookies usually will not be available until the page is reloaded / refreshed, which is why you're not getting the value that you're expecting. You'd really have to do the payment calculation in PHP and store it in a $_SESSION if you're looking for it to persist like a cookie.

How to pass javascript variables to php variables with yii

First: I KNOW this is a duplicate. I am creating this because none of the answers to all the other questions satisfy me. I have a very particular situation where I'm using yii and tryi I can't send it through ajax because the php and javascript are on the same page on the same page.
Basically what I'm asking is if you have a page that uses yii and chart js, and you need to render a page that requires two arguments from the clicked bar, which is represented by activeBars[0]:
<script>
canvas.onclick = function(event) {
var activeBars = getBarsAtEvent(event);
<?php $controller->functionThatRendersView($arg1 /**(activeBars[0].value*/,$arg2 /**(activeBars[0].label*/); ?>
}
I don't care if it will render automatically, that is another problem. I just need to get those arguments to the php.
Thanks.
Also, if it helps, I am passing those two values to javascript through php for loops:
labels: [<?php for ($i=1;$i<=$numberIssues;$i++) {
echo $i . ",";
}?>],
The problem with grabbing $i and putting it into the label argument is that I don't know which bar label is the clicked one, I need javascript to pass the clicked bar values back to php.
Explain to us again why you can't use ajax. You say "because the php and javascript are on the same page". That's not what ajax is - you need a different URL for the ajax request, and a separate PHP file or something to handle it.
Without ajax it's impossible for javascript to send information to PHP, because the PHP runs on the server before the javascript runs on the client. Unless of course you want to do a complete page refresh, which is slower and generally worse from the user perspective.
I found an answer to my question! I'm just doing this for anyone else who is stumbling:
To pass javasctipt variable var jsInteger = 5; to php you type (in javascript):
window.location.href = "yourPhpFile.php?phpInteger="+jsInteger;
You access the variable in php like so:
$phpInteger = $_GET['phpInteger'];
This will require a page refresh, and will redirect you to the php file.

Store javascript data into PHP SESSION VARIABLE?

I'm wondering if it's possible to store a number generated from a javascript script into a PHP SESSION variable. I basically want to store my code '+.res.id+' and '+.res.level+' into a PHP SESSION. Those 2 javascript codes generate a random number and inputs that number in a html form. IS there anyway I could take that number and store it in a PHP SESSION? For example
<script>
JAVASCRIPT CODING
'+res.level+'
'+res.id+' // BTW it actually does generate a number I just can't echo it in another page or store it in a SESSION
</script>
<?php
$_SESSION['.res.id.'] = $idnum;
$_SESSION['.res.level.'] = $levelnum;
?>
Then after in a seperate page I want to call that SESSION and echo the number that the code generated. But my only problem is that when I echo the $_SESSION it echo's as ".res.id." instead of the randomly generated number. How do I fix this to make it echo the random generated number?
First of all javascript is running on a client side and php is running on a server side. It means you can't just store the generated number. But there is a workaround on that. You can do that by means of AJAX request.
In your js you can do this.
var res_id = your_random_number;
var res_level = your_random_number
$.post("/any/url/that/contains/your/php/code", {res_id:res_id, res_level:res_level});
In your php.
$_SESSION["res_id"] = $_POST["res_id"];
$_SESSION["res_level"] = $_POST["res_level"];

I can't get a value from a PHP array...?

I'm writing a script to retrieve the scores from an osu! beatmap. The script uses the osu! API, which can be found here. I've obtained a valid API key, and got the info from the website. My project can be found here: failosu!.
This script is called by AJAX, and the variable s is passed via POST.
My problem is with the returned array.
In the following snippet (not really, it's pretty much my entire script), I make a request for the beatmap information first. In doing this, I am passing a variable, s (beatmap set ID), to the server, and trying to get the variable b (beatmap ID).
However, whenever I call $d1['beatmap_id'], it doesn't return anything to the main page. Instead, my AJAX script runs the error function rather than the success function. Does anyone know what my problem is?
if($_POST['id']) {
$s = $_POST['id'];
$k = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$u0 = "https://osu.ppy.sh/api/get_beatmaps?k=".$k."&s=".$s;
$d0 = json_decode(file_get_contents($u0));
$d1 = get_object_vars($d0[0]);
$b = $d1["beatmap_id"];
// THE CODE STOPS WORKING HERE FOR SOME REASON ????
$u = "https://osu.ppy.sh/api/get_scores?k=".$k."&b=".$b."&m=0";
echo $u;
$d = json_decode(file_get_contents($u));
for($i=0;$i<count($d);$i++) {
echo "<li>".$i." ".$d[$i]['username']."</li>";
}
}
Does anyone know what's wrong? Do you need me to tell you more information about my code?

Categories