How to Store JavaScript Variable Output into a PHP Variable

How can I store JavaScript variable output into a PHP variable?

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).

With that in mind, the closest you could come is to use a PHP variable in your JS:

<?php
$a = 'foo'; // $a now holds PHP string foo
?>
<script>
var a = '<?php echo $a; ?>'; //outputting string foo in context of JS
//must wrap in quotes so that it is still string foo when JS does execute
//when this DOES execute in the browser, PHP will have already completed all processing and exited
</script>
<?php
//do something else with $a
//JS still hasn't executed at this point
?>

As I stated, in this scenario the PHP (ALL of it) executes FIRST at the server, causing:

  1. a PHP variable $a to be created as string 'foo'
  2. the value of $a to be outputted in context of some JavaScript (which is not currently executing)
  3. more done with PHP's $a
  4. all output, including the JS with the var assignment, is sent to the browser.

As written, this results in the following being sent to the browser for execution (I removed the JS comments for clarity):

<script>
var a = 'foo';
</script>

Then, and only then, will the JS start executing with its own variable a set to "foo" (at which point PHP is out of the picture).

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.

To store JavaScript variable output into a PHP variable and to database?

To pass the data throught url you should use "?" character

your script

 window.location.href = window.location.href+'#reason='+answer;</script>

how it should be

window.location.href = window.location.href+'?reason='+answer;</script>

Reformating your code:

if(!empty($_GET['status']) && $_GET['status'] == "Rejected") {
if(!empty($_GET['reason'])) {
$reason = $_GET['reason'];
$approve="UPDATE approveleave SET status='Rejected',rejectreason='".$reason."' WHERE id='".$id."'";
$result2=mysql_query($approve,$con);
header("location: /registration.php");
} else {
?>
<script type='text/javascript'>
var answer = prompt('Please enter');
var a = document.write(answer);
window.location.href = window.location.href+'?reason='+answer;
</script>
<?php
}
}

Use empty() function to check if a array is empty or not.

Note:
The isset() is used to check if a variable is defined or not.

The best way to interact with database is PDO.
Don't use mysql_query() because it is deprecated in the newer versions of Php.
You can use mysqli instead.

PHP: Store Result of JavaScript Function into a PHP Variable

PHP is a back-end language and can't detect front-end events such as click, change, etc.

In your larger code, the value of x will only be defined once the event is fired(onchange), that's when the select input changes. Javascript works that way, but PHP doesn't. Once PHP sends a response the first time, its job is done.

This is when you will want to use forms or Ajax.
Using forms would be a good start.

Quick note, it's good practice to try to keep HTML, CSS and JS separate from PHP as much as possible.

...
$result = mysqli_query($mysqli, $query);

?>

<form method='post' action='insert.php' /> <!-- Link to php file to insert data to database -->
<select name ='names' id='myselect' onchange = "myFunction()">
<?php
while ($row = mysqli_fetch_array($result)){
echo "<option value = '" . $row['custID'] . "'>" . $row['Customer_Name'] . "
</option>";
}
?>
</select>
<input type="submit" value="submit" /> <!-- You will need a button to submit the data -->
</form>

<p>When you select a customer name, a function is triggered which
outputs the ID of the selected customer.</p>
<p id="demo"></p>

And now your insert.php file would look like:

<?php 

// Get data from that was posted from the form
$customer_id = $_POST['names'];

// Now do whatever with the customer ID
echo $customer_id;

How do I pass JavaScript variables to PHP?

You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.

You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.

<DOCTYPE html>
<html>
<head>
<title>My Test Form</title>
</head>

<body>
<form method="POST">
<p>Please, choose the salary id to proceed result:</p>
<p>
<label for="salarieids">SalarieID:</label>
<?php
$query = "SELECT * FROM salarie";
$result = mysql_query($query);
if ($result) :
?>
<select id="salarieids" name="salarieid">
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
}
?>
</select>
<?php endif ?>
</p>
<p>
<input type="submit" value="Sumbit my choice"/>
</p>
</form>

<?php if isset($_POST['salaried']) : ?>
<?php
$query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
$result = mysql_query($query);
if ($result) :
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
echo '</tr>';
}
?>
</table>
<?php endif?>
<?php endif ?>
</body>
</html>

Storing JS output in a PHP variable

Yes, you should use AJAX.

Note that JS (the way you intend to use it) runs on the client side (in the browser) and php runs on a server, which in many cases results in asynchronous communication, hence AJAX.

In your JavaScript code, you need to create a XMLHttpRequest object that can handle the communication:

var xhr = new XMLHttpRequest();

An example on how to receive the answer from the server:

xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200) {
// do something with xhr.responseText
}
}
}

An example on how to send the data:

xhr.open("POST", "serverside.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(content);

content will be the data you send to the server, e.g. "c=HelloWorld"

In your php script at the server side, you need to handle the received data. It can look something like this:

<?php    

if (isset($_POST['c'])) {
echo htmlspecialchars($_POST['c'], ENT_QUOTES, 'UTF-8');
}

?>

The server should then respond with 'HelloWorld'.



Related Topics



Leave a reply



Submit