JavaScript

How to pass JavaScript variables to PHP

JavaScript is the client-side language and PHP is the server-side scripting language. In this tutorial, we will find out how to pass a variable from JavaScript to PHP via an HTTP request.

On the JavaScript side, the request usually involves passing a value from JavaScript to PHP. Either the URL as a parameter (which PHP retrieves it through the $_GET array) or through a POST-like request (like when someone submits a login form and PHP retrieves it through the $_POST array).

Now you can dynamically create this URL through JavaScript and send it to the server through an AJAX call (like jQuery’s .ajax method) or through something like JavaScript.location.href = URL;. In this URL, you will have the data you want to send to PHP. Below is an example of a JavaScript function that can be called by pressing a button.

<?php
	function add() {
		var a = 1;
		var b = 2;

		window.location.href = "add.php?var1=" + a + "&var2=" + b;
	}
?>

In this function above, we have two JavaScript variables in the URL. We then tell “window” to access the “add.php” page with the two parameters “var1” and “var2” which contain the data. Here we are passing two variables from JavaScript to PHP. The browser would then access the URL http://www.exemple.com/add.php?var1=1&var2=2.
 

 

Reception and processing of variables in PHP

Now that JavaScript has issued the request and passed some parameters, PHP can retrieve the data in the $_GET array.

<?php
	function add() {
	   // Check if var1 and var2 parameters are passed to the script via the URL
	   if (isset($_GET["var1"]) && isset($_GET["var2"])) {

		  $s = $_GET["var1"] + $_GET["var2"];

		  echo $_GET["var1"]." + ".$_GET["var2"]." = ".$s;
	   }
	}
?>

This code will display the sum of the two variables sent from the JavaScript code:
 
Output:

1 + 2 = 3
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

One thought on “How to pass JavaScript variables to PHP

  • I have tested this code:

    *Write the code at the end of the PHP page!

    jsVar=document.getElementById(“tag_id”).innerHTML;
    alert(jsVar);

    ?php
    $phpVar=’document.write(jsVar);’;
    echo $phpVar;
    ?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *