How to Use a JavaScript Variable as a PHP Variable

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>

How can I use a JavaScript variable as a PHP variable?

PHP is run server-side. JavaScript is run client-side in the browser of the user requesting the page. By the time the JavaScript is executed, there is no access to PHP on the server whatsoever. Please read this article with details about client-side vs server-side coding.

What happens in a nutshell is this:

  • You click a link in your browser on your computer under your desk
  • The browser creates an HTTP request and sends it to a server on the Internet
  • The server checks if he can handle the request
  • If the request is for a PHP page, the PHP interpreter is started
  • The PHP interpreter will run all PHP code in the page you requested
  • The PHP interpreter will NOT run any JS code, because it has no clue about it
  • The server will send the page assembled by the interpreter back to your browser
  • Your browser will render the page and show it to you
  • JavaScript is executed on your computer

In your case, PHP will write the JS code into the page, so it can be executed when the page is rendered in your browser. By that time, the PHP part in your JS snippet does no longer exist. It was executed on the server already. It created a variable $result that contained a SQL query string. You didn't use it, so when the page is send back to your browser, it's gone. Have a look at the sourcecode when the page is rendered in your browser. You will see that there is nothing at the position you put the PHP code.

The only way to do what you are looking to do is either:

  • do a redirect to a PHP script or
  • do an AJAX call to a PHP script

with the values you want to be insert into the database.

Use javascript variable in php code

You can't use javascript variable in php code. Php code run's on the serverside and javascript code runs in the client side. You can't ask the browser to run php code.

Your variable loc will have a value only when the code reaches the browser.

If you want to get some value from server and combine it with javascript variables then do the following.

Use an ajax request and send the desired values to server. The server will return with a response. Use that response text and store it in your action variable.

How to get JavaScript variable value in PHP

You will need to use JS to send the URL back with a variable in it such as:
http://www.site.com/index.php?uid=1

by using something like this in JS:

window.location.href=”index.php?uid=1";

Then in the PHP code use $_GET:

$somevar = $_GET["uid"]; //puts the uid varialbe into $somevar

How to use javascript variables in PHP

One way of doing it is to make use of a hidden text/input box.

<input type="text" style="display:none" id="hiddenVal" />

In the Javascript assign the variable to the input box.

<script>
function loadValues()
{
var abc = 'this is text';
document.getElementById("hiddenVal").value = abc;
//alert(document.getElementById("hiddenVal").value);
}
</script>

<body onload="loadValues();">

<form action="processing.php" method="post">
<input type="text" style="display:none" id="hiddenVal" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>

This is one method to allow you to use Javascript variable and post it to the backend. Alternatively if you want to display these values just remove the

style="display:none"

on the control.

Now after the post occurred one should be able to pick up the variable using processing.php

<?php
echo $_POST["hiddenVal"];
?>

Very dirty way of doing this but does the trick.

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.

Get Javascript Variable value in PHP variable

use this code for use variable

  <?php
session_start();
echo $_SESSION['php_value'];
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function getValue(obj){
var value = obj.value;
$.ajax({
type:"POST",
url: 'edit.php',
data: "val="+ value,
dataType: 'text',
async: false,
cache: false,
success: function ( result ) {
window.location.reload();
}
});
}

</script>

<select onchange="getValue(this)">
<option value="1" <?php if($_SESSION['php_value'] == 1) echo 'selected';?>>One</option>
<option value="2" <?php if($_SESSION['php_value'] == 2) echo 'selected';?>>Two</option>
<option value="3" <?php if($_SESSION['php_value'] == 3) echo 'selected';?>>Three</option>
<option value="4" <?php if($_SESSION['php_value'] == 4) echo 'selected';?>>four</option>

</select>

then create edit.php file

<?php
session_start();
$_SESSION['php_value'] = $_REQUEST['val'];
?>

How to assign the javascript variable value to php variable

Javascript works on the user's computer, PHP works on your server. In order to send variables from JS to PHP and vice versa, you need communication such as a page load.

Have a look here on what you can do: How to pass JavaScript variables to PHP? or more specifically the first answer (https://stackoverflow.com/a/1917626/1311593)



Related Topics



Leave a reply



Submit