How to Pass Variable from PHP to JavaScript & JavaScript to PHP

In this tutorial, I will show you how to pass a variable from PHP to JavaScript and JavaScript to PHP. It means you will be able to exchange variables between server side and client side.

How to Pass Variable from PHP to JavaScript & JavaScript to PHP

Why you need to pass variable from PHP to JavaScript and JavaScript to PHP?

If you have a value that is dynamically generated by PHP (Server Side), and you want to use that value in JavaScript – or, that value is dynamically generated by JavaScript and you want to use that value in PHP, then this tutorial is for you. So, keep reading this post.

Pass variable from PHP to JavaScript

Passing a variable – dynamically generated by PHP to JavaScript is quite easy. Because, server side always comes first and then client side second. So, here is how we do it as codes below.

Explanation of the code above

On line 2, we’ve assigned a string to PHP variable with name $php_var in PHP.

On line 11, we’ve assigned the same string to a JavaScript variable with name js_var by just simply echoing from PHP. As PHP (Server Side) comes first, so – JavaScript seeing this as a plain regular string, – not as any code (like this: var js_var = “Hello world from PHP”;).

Pass variable from JavaScript to PHP

Passing a variable is not that simple. Unlike before, we have used get method to send a JavaScript variable to PHP. Using regular JavaScript, it is not possible to exchange a value from JS to PHP without sending the value to the server. So, you have to reload the page to make it working.

Pass variable from JavaScript to PHP without reloading the page using AJAX

To pass variable from JavaScript to PHP without reloading the page, we need AJAX. To do that, try the codes below.

js_to_php_using_ajax.php

process.php

There are some limitations in the script above. You cannot work with the final value in PHP on the same page (js_to_php_using_ajax.php). But you can work further with that on process.php.

If you’re reading this article then I assume that you have knowledge on PHP, JavaScript, HTML. If you need help on fetching data using AJAX, then I recommended you to see this post -> How to Load Content from XML, JSON, Text File by jQuery AJAX.

Hope you understood the logic behind passing or exchanging values between server side and client side scripting language. If you need any help, just leave a comment, I’ll be back to you.

Thank you!