pass value from javascript to php

How to pass value from JavaScript to PHP

This post has been viewed 138 times.

In this tutorial we would be learning on how to pass value from JavaScript to PHP.

Are you looking for PHP to JavaScript and not this one? You might want to view How to pass value from PHP to JavaScript instead.

What you’ll need:

  • Basic JavaScript and PHP knowledge.

Step 1: Create an HTML file.

For this example, we would create an HTML file named index.html, this file will contain our client-side scripts.

Step 2: Include a jQuery file.

We would be needing this additional library to perform asynchronous communication with the server from the browser or client.

Step 3: Declare the JavaScript variable.

In this example we would be passing the string Hello World! from JavaScript to PHP.

Step 4: Create a PHP file.

You need to create a PHP file that will contain our server-side scripts. For this example, we would be creating a file named ajax.php in the same directory with the file created in Step 1.

Step 5: Declare the PHP variable.

This PHP variable is initialized in the file ajax.php.

Step 6: Create an AJAX call.


You should include this code after the declaration of our JavaScript variable. The method type that will be using is POST.

If you are familiar with the form method is that there are POST and GET methods, the type in this are just the same.

The value for the url is the file that we have created in Step 4.
The value for the data is the variable name of our JavaScript variable declared in Step 3.

For the success and error function, you can handle the result of our AJAX call. If the call succeeds then do something in the success function, and the same with the error function, just in case our script fails.

Step 7: Assign the JS variable to the PHP variable.

Since the value for the data in Step 6 is myJSVar and the type is POST we would be using the POST variable in the server-side containing the variable for data.

Complete code:



That’s it, we have successfully passed the value from JavaScript to PHP. I hope you learned something.

Hello, I am a freelance website and mobile application developer. I am also the owner of this website, so if you have any projects for me you can contact me at [email protected] or use the contact page. When I’m not doing some work, I can be found watching Anime/Asian Dramas/American TV Series, playing computer games, and writing tutorials on this website. I run the program repeatedly hoping the error won’t show up next time.