The Basics of Passing Values From JavaScript to PHP and Back

Passing Variables Between JavaScript and PHPOne of the common questions I often run into from new programmers to JavaScript or PHP is how to pass values back and forth between the two. The quagmire is that JavaScript is a client side language (most of the time) and PHP is a server-side language. Once you know how the process works when someone submits some data on the front end, and how it is manipulated and returned on the back end, it is easy to see how you can exchange information between the languages.

PHP to JavaScript

When you visit a PHP page for the first time (or any website that has a server-side language generating its pages) your browser first requests a page from the server. The server in turn takes the request, calls PHP to build the page and manipulate variables, then returns the results back to the user in the form of HTML, a string, XML, JavaScript and more.

With the first request you typically don’t have any immediate data you are sending back through JavaScript. So PHP returns some JavaScript that is pretty standard and generic like handling form validation or perhaps some basic functions. When PHP prints the results it can also stick in values that it has for variables. For instance it may print out the message “Hello World” which is contained in the variable $hello.

echo "Just wanted to say $hello";

Keep this part in the back of your mind for a second as we will return to the idea of this variable in a second.

JavaScript to PHP

On the JavaScript side the way you typically pass a value from JavaScript to PHP is through the request. Either the URL as a parameter (which PHP will see come in through the array $_GET) or through a post request (like when someone submits a login form and PHP will see it come in through the array $_POST).

Now you may build this URL dynamically through JavaScript and send it to the server through either an AJAX call (like jQuery’s .ajax method) or through something like a JavaScript window.location.href = URL; type of mechanism. In that URL you would have the data you want to send to PHP. Below is an example of a JavaScript function which might be called on the pressing of a button…

function sayHelloWorld() {
    var hello = "hello";
    var world = "world";

    window.location.href = "somepage.php?w1=" + hello + "&w2=" + world;

In this function above we have two JavaScript variables which are concatenating into a URL. We then tell the window to go to this PHP page with the two parameters “w1” and “w2” which holds the data. Here we are essentially passing two variables from JavaScript to PHP. The browser would then go to the URL

PHP Receiving and Processing The Variables

Now that JavaScript has issued the request, and passed some parameters, PHP can see the data coming in through its $_GET array and use it to build our PHP from earlier “$hello”. Now again since we did this through the passing of parameters in a URL, PHP is going to see them as $_GET. If we had stuck these values in some form and submitted the form using JavaScript, PHP would have seen them in the $_POST array. So be mindful of the method you are using to pass the data.

With the PHP arrays we can read in the values, manipulate them as we see fit (like to build queries or fetch some sort of data) and then stick our results back into some new JavaScript which we will print to the user. Remember, PHP prints the JavaScript with the results. That is how it gives info back to JavaScript. PHP prints its results and is unaware that the request came from JavaScript. It sees the request as just any other browser request.

Below is an example of a function that we would print back to the user. Notice that the PHP function is printing a JavaScript function which it is dynamically building…

function sayHiBack() {
   // Check if we have parameters w1 and w2 being passed to the script through the URL
   if (isset($_GET["w1"]) && isset($_GET["w2"])) {

      // Put the two words together with a space in the middle to form "hello world"
      $hello = $_GET["w1"] . " " . $_GET["w2"];

      // Print out some JavaScript with $hello stuck in there which will put "hello world" into the javascript.
      echo "<script language='text/javascript'>function sayHiFromPHP() { alert('Just wanted to say $hello!'); }</script>";

This code would then print out the JavaScript function “sayHiFromPHP” which then other JavaScript could call as a normal function and it would print out the $hello you got from PHP. We could have also called this function on window load or some other event.

The Power of JavaScript AJAX in This Situation

We touched on this earlier but this process can also be done with an AJAX call from JavaScript. Here the JavaScript would put together a URL with the parameters it wants to pass to PHP. Just like we did in the examples above. PHP would see the parameters again through $_GET or $_POST depending on the method you use to submit the data. It would work with the data, generate some results which it returns to the browser as if it was printing a normal page. But this time it is being returned as a result to JavaScript. Meaning that once the page returns it is going to return the HTML source code right back to the AJAX call in JavaScript. From there JavaScript can then manipulate the data as it sees fit.

This process is pretty much the same as I just described but with the AJAX call it is shortened because JavaScript is going to get the result of the PHP back directly. PHP is still unaware of JavaScript and is printing results like it would to the browser. This method is especially useful if you have your PHP printing something simple like a table or even a simple string of text.


In this article we explained the process by which JavaScript and PHP can communicate. When we first visit the page, the normal page content is printed. The user does something which triggers some data to be added to a URL or posted through a form dynamically using JavaScript. That JavaScript submits the data to PHP which sees the input coming in through the $_GET or $_POST arrays. It pulls that data out, manipulates it, constructs a response in the form of some JavaScript and sends it back to the user. The user can then execute that JavaScript.

We then briefly touched on the process by which JavaScript shortens the process using AJAX to both send the data to PHP and waits for the info to be processed and then directly receives the data back into JavaScript for further manipulation.

Once you get the process down, I recommend you play more with the AJAX method since it is often quicker and more dynamic. When you get the hang of it, AJAX will make the page seem more fluid and responsive since it doesn’t require the entire page to refresh.

Thanks again for reading and good luck with your JavaScript/PHP projects! 🙂

Update: As pointed out by one of our commenters the code in this article is meant to show you the process by which the two languages can communicate. It is up to you to make sure that you properly validate all incoming data to PHP and also to encode and properly display the JavaScript returned by PHP. DO NOT simply cut and paste into a production environment. Thanks!

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks “The Programmers Idea Book” and “Diagnosing the Problem” . He has been a programmer for over 18 years. He works for a hot application development company in Vancouver Canada which service some of the biggest telecoms in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.

  • Wow. What about all the security holes you open up, in both examples?!

    • These examples are just that, examples, not literal code you should throw right in production. This code will need proper validation of incoming data of course. I wrote this with simplicity in mind to get across the process. All data coming in from the user should be fully validated. 🙂

      • Unsuspecting people *will* copy and paste these examples and adopt them directly for use: the word security doesn’t appear in your article. How are they going to know that you’ve included classic XSS attacks in there for them? It’s an unknown unknown to them.

        • Curious, how do you go about getting PHP and JavaScript to talk to one another? I would love an alternative view. Sometimes it is more helpful to be constructive than just crying out “security hole security hole” and propose no real solution. And please, don’t say you would just use some library because that is not going to help anyone.

          • uhm, what. Okay, let’s see:

            window.location.href = “somepage.php?w1=” + hello + “&w2=” + world;

            Depending on the true source of hello and world, you’re almost always introducing a bug here: what if hello or world contained an ampersand? Fix:

            window.location.href = “somepage.php?w1=” + encodeURIComponent(hello) + “&w2=” + encodeURIComponent(world);

            Okay, that wasn’t hard. We encode the data we’re inserting into URI components with encodeURIComponent. See:

            And for the reverse direction:

            echo “function sayHiFromPHP() { alert(‘Just wanted to say $hello!’); }”;

            What happens if someone visited your site with the ‘w1’ query string var set to the following?

            ‘); alert(‘I am evil and will now steal your site cookies.’); … some code to spirit away window.cookie’s value … trash = (‘

            Set w2 to whatever else. The PHP would output:

            function sayHiFromPHP() { alert(‘Just wanted to say ‘); alert(‘I am evil and will now steal your site cookies.’); … some code to spirit away window.cookie’s value … trash = (‘ w2!’); }

            That ain’t good, y’know; cookie stealing leads to session hi-jacking, etc. Fix:

            echo “function sayHiFromPHP() { alert(‘Just wanted to say ‘ + ” . json_encode($hello) . ” + ‘!’); }”;

            This safely escapes $hello in a manner suitable for inclusion in JavaScript as a string literal. See A quick test shows it also escapes backslashes (to prevent someone entering as an attack), at least in late versions. The docs say the option was added in 5.4.0, but it’s possible it was merely not switchable before then.

            It’s bad teaching to pretend like this doesn’t exist or doesn’t matter: this is the genesis of minds adapted poorly for thinking about security seriously when it actually matters later. At the very least, a passing mention and reference to somewhere else where these needs can be met is necessary — not pretending it’s a non-issue or that people will magically work it out later, especially seeing as you yourself didn’t seem to have the answers.

          • You see but that is the problem. You have no additional approach, you have just introduced the validation pieces to it. As I clearly state in my first reply to you was left out for simplicity. Putting all that stuff in the code would only cloud the process and cause people to abandon the approach. I have already said that one will need to include proper validating and it won’t be an issue. Thanks for the feedback. It is appreciated.

          • Better they abandon the approach than perform it in such a manner! 🙂 Thanks for the replies.

          • varex morgan

            So smart he provides no tutorials on the matter but complains about the one given. A quick goggle search will reveal validation techniques. thanks for this great tutorial The Coders Lexicon. More over it’s safe to say if validation is not in the developers mind the rest of his code is not validated.

  • Jared Green (aka Bladeoz)

    Excellent article Martyr2 -> All I was after was a description of the simple connection between the two languages as I have been thrown into a very complex system that will not reveal it’s secrets readily.

    Really appreciate the simple read 🙂

    • Thanks for the reply. I too have experienced complex systems which I was thrown into and poorly documented. Just power through is all you can do. 🙂

      • Jared Green (aka Bladeoz)

        Thanks again mate – will do! haha 🙂

  • Glenn Rieger

    When I need to pass a var back to PHP I use a hidden input in PHP (e.g. ) and then set in it js (e.g. ‘input[name=”var”]’).val(var); ). I can then access it using $_POST[‘var’] . no need to dick around with calling the PHP…

    • And yeah that is certainly one way you could do it when it comes to the posting of variables. I just provided an example which uses the query string. In both cases you are still passing the values to the PHP script however. The other part of the example was how you could have PHP then post back to the client using JavaScript. Of course that part would be transparent with AJAX.

      Thanks for the comment. 🙂

  • nice and thanks

  • Great help, thanks

    what about get php variable in javascript ?

  • Sea Sun

    Thanks for great help !!!

  • krishan kant Sharma

    how can we assign java script variable to php variable? PLz help me