How to Get JavaScript Function Data into a PHP Variable

How to get JavaScript function data into a PHP variable

Use jQuery to send a JavaScript variable to your PHP file:

$url = 'path/to/phpFile.php';

$.get($url, {name: get_name(), job: get_job()});

In your PHP code, get your variables from $_GET['name'] and $_GET['job'] like this:

<?php
$buffer_data['name'] = $_GET['name'];
$buffer_data['job'] = $_GET['job'];
?>

How do I pass variables and data from PHP to JavaScript?

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

In no particular order:

  1. Use AJAX to get the data you need from the server.
  2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
  3. Echo the data directly to JavaScript.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

1. Use AJAX to get the data you need from the server

This method is considered the best, because your server side and client side scripts are completely separate.

Pros

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for asynchronous data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.

Cons

  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g., if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

Implementation Example

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

get-data.php

/* Do some operation here, like talk to the database, the file-session
* The world beyond, limbo, the city of shimmers, and Canada.
*
* AJAX generally uses strings, but you can output JSON, HTML and XML as well.
* It all depends on the Content-type header that you send with your AJAX
* request. */

echo json_encode(42); // In the end, you need to echo the result.
// All data should be json_encode()d.

// You can json_encode() any value in PHP, arrays, strings,
//even objects.

index.php (or whatever the actual page is named like)

<!-- snip -->
<script>
function reqListener () {
console.log(this.responseText);
}

var oReq = new XMLHttpRequest(); // New request object
oReq.onload = function() {
// This is where you handle what to do with the response.
// The actual data is found on this.responseText
alert(this.responseText); // Will alert: 42
};
oReq.open("get", "get-data.php", true);
// ^ Don't block the rest of the execution.
// Don't wait until the request finishes to
// continue.
oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

Some more reading material

  • Using XMLHttpRequest - MDN
  • XMLHttpRequest object reference - MDN
  • How do I return the response from an asynchronous call?

2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

Pros

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.

Cons

  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JavaScript that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

index.php

<!-- snip -->
<div id="dom-target" style="display: none;">
<?php
$output = "42"; // Again, do some operation, get the output.
echo htmlspecialchars($output); /* You have to escape because the result
will not be valid HTML otherwise. */
?>
</div>
<script>
var div = document.getElementById("dom-target");
var myData = div.textContent;
</script>
<!-- snip -->

3. Echo the data directly to JavaScript

This is probably the easiest to understand.

Pros

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.

Cons

  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

Implementation is relatively straightforward:

<!-- snip -->
<script>
var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>
<!-- snip -->

Good luck!

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 to pass JavaScript variable into a PHP function parameter?

In a very simple form/example you simply need to send an http request ( here done using the Fetch api ) to your PHP script and intercept that request. The following sends a POST request with a single parameter sid which is then passed to the Twilio method as per your requirement.

<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['sid'] ) ){
$sid=$_POST['sid'];
exit( $twilio->check_disputed( $sid ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Your page</title>
</head>
<body>
<h1>Do lots of things...</h1>

<script>
/*
do whatever it is you do to create your variable sid
- here it is explicitly declared rather than derived.
*/
const sid='CA519c6aefde211131f2f44370d67607d4';

let fd=new FormData();
fd.set('sid',sid);

fetch( location.href, { method:'post', body:fd } )
.then(r=>r.text())
.then(data=>{
alert(data)
})
</script>
</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.

passing a php variable into javascript function

If it's not a number, you need to quote it:

<?php
echo '<td align="center" ><a href="javascript:product(\''.$product_id.'\');">
<br/> '.$row['product_name'].'</a></td>';
?>

Or, a neater way, use php just when needed (no PHP tags around, it's HTML with inserted PHP):

<td align="center" ><a href="javascript:product('<?= $product_id ?>')"> 
<br/><?= $row['product_name'] ?></a></td>

You can also define a JavaScript value and assign the PHP value to it and then use it, like:

var pid = '<?= $product_id ?>'; // then call product(pid)
etc...

EDIT

Code fix.

This:

<?php
...
// php stuff
...

echo '<tr> ';
echo '<td align="center" >'.$number.'</td>';

echo '<td align="center" ><a href="javascript:product('<?= $product_id?>')">
<br/>'<?= $row['product_name']?>'</a></td>';

echo '<td align="center"><a href="javascript:company()" ><br/> '.$row['company_name'].'</td>';
echo '<td align="center"><a href="javascript:category()" ><br/> '.$row['category_name'].'</td>';

$number=$number+1;

}echo '</tr>';
echo'</table>';
echo'</center>';

Can become something like this:

<?php
...
// php stuff
...

?> // close the PHP tag and switch to HTML
<tr>
<td align="center" ><?= $number ?></td>
<td align="center" ><a href="javascript:product('<?= $product_id?>')"> <br/>'<?= $row['product_name']?>'</a></td>

<td align="center"><a href="javascript:company()" ><br/> <?= $row['company_name'] ?></td>
<td align="center"><a href="javascript:category()" ><br/> <?= $row['category_name'] ?></td>

<?php // reopen PHP tag when needed
$number++; // incrementation simplified
}
?> // close again
</tr>
</table>
</center>

Something like that.

Also, read here about the deprecated mysql_* functions and why you should switch to mysqli_* or PDO.

Get value from a javascript function in a php variable

To allow your JavaScript to communicate with your PHP backend, you'll have to use Ajax. This allows you to send information to a PHP file.

For the sake of keeping it simple, I suggest you use jQuery, it has two useful methods you can use $.ajax and $.get

Your JavaScript could look something like this:

$(document).ready(function(){
var timeToSend = calcTime(city, offset,selDate,selHours,selMinutes);

//we are sending information to saveTimeToDB.php
$.ajax('saveTimeToDB.php', {
data: {time:timeToSend}//this is an object containing all the information you want to send
}).done(function(){
//a function which gets called if the ajax call succeeded
alert('the time has been saved');
}).fail(function(){
//a function which gets called if the ajax call failed
alert('Uh-oh, something went wrong. We did not save the time');
});
});

In the 'saveTimeToDB.php' file you can now access this variable with:

$time = $_GET['time'];

You should then be able to use this variable and insert it in your database.

Make sure to do many checks on this variable, to make sure you're not injecting anything malicious in to your DB.

Use PHP variable as Javascript function parameters

Seems like you forgot about quotes, when you are passing strings into function.

<script>
$(document).ready(function () {
autoFill('{{ $dropDown }}', '{{ $emptyDropDown }}');
});
</script>

You can do it this way, but you shouldn't, because Laravel Blade do it for you itself.

<?php echo "<script> autoFill('".$dropDown."', '".$emptyDropDown."'); </script>"; ?>

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



Related Topics



Leave a reply



Submit