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.
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.
<?php $php_var = "Hello world from PHP"; ?> <html> <head> <title>Pass variable from PHP to JavaScript - Cyberster's Blog'</title> </head> <body> <script> var js_var = "<?php echo $php_var; ?>"; alert(js_var); </script> </body> </html>
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.
<html> <head> <title>Pass variable from PHP to JavaScript - Cyberster's Blog'</title> </head> <body> <a href="#" id="link">Click me!</a> <script> var js_var = "<br />Hello world from JavaScript"; document.getElementById("link").onclick = function () { window.location = "?js_var=" + js_var; } </script> <?php if (isset($_GET['js_var'])) $php_var = $_GET['js_var']; else $php_var = "<br />js_var is not set!"; echo $php_var; ?> </body> </html>
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
<html> <head> <title>Pass variable from PHP to JavaScript - Cyberster's Blog'</title> </head> <body> <a href="#" id="link">Click me!</a> <div id="update"></div> <script type="text/javascript"> var js_var = "<br />Hello world from JavaScript"; document.getElementById("link").onclick = function () { // ajax start var xhr; if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE var url = 'process.php?js_var=' + js_var; xhr.open('GET', url, false); xhr.onreadystatechange = function () { if (xhr.readyState===4 && xhr.status===200) { var div = document.getElementById('update'); div.innerHTML = xhr.responseText; } } xhr.send(); // ajax stop return false; } </script> </body> </html>
process.php
<?php if (isset($_GET['js_var'])) $php_var = $_GET['js_var']; else $php_var = "<br />js_var is not set!"; echo $php_var; ?>
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!
Pass variable from PHP to JavaScript – Cyberster’s Blog’
Click me!
var js_var = “Hello world from JavaScript&raj=developer”;
document.getElementById(“link”).onclick = function () {
window.location = “?js_var=” + js_var;
}
<?php
if (isset($_GET['js_var'])) $php_var = $_GET['js_var'];
else $php_var = "js_var is not set!”;
echo $php_var;
?>
In above code $_GET[‘js_var’] not taking the value after the ‘&’ symbol.
echo $php_var; not printing the value after the & symbol in js_var.
Please solve my problem…….
Hi Raaj,
In your code above, your prepared URL is not encoded. An ampersand (‘&’) in any URL works as a variable separator.
Thats why the get method detecting two variables in the URL (js_var and raj). If you echo $_GET[‘raj’]; – you will get ‘developer’ printed.
You need to encode the ampersand (‘&’), to set it as a character within a string.
You can do this in two ways, 1. JavaScript way, 2. PHP way,
1. JavaScript way: I recommend this
or
2. PHP way: If you need entire query string, use this
thank’s a lot Das…….
Hey, nice post!!
I just got a question, how can I redirect the js value to process.php? ’cause it looks like you’re not using that file at all…
Hi Laia,
I showed three different methods:
You are talking about the third method. I’m making an AJAX request here to the process.php. I’m sending the JS variable via URL and getting the same from process.php using get method. You’ll have access to the JS variable from php, only in the process.php, not js_to_php_using_ajax.php
To use that value, go further with process.php
Thanks
I am using it with an onchange event for a select input and it is not working
var js_var = “Hello world from JavaScript”;
document.getElementById(“page”).onchange = function () {
window.location = “?js_var=” + js_var;
}
Hi David,
JavaScript onchange event works only for <input>, <select>, and <textarea> tags. You have not provided the HTML, so I guess your element with id=”page” is not <input>, <select>, or <textarea>.
If you’re using script tag with same page of your HTML, then move it to the bottom of your page. If you are using an external JavaScript, then call your code from a window.onload event.
Here is a working code for you:
I guess my code will be work too.
`
var a=’abc’;
<?php
$b='document.write(a)’;
echo $b;
?>
`
Hi krishna,
If you’re trying to pass variable from JavaScript to PHP, your code wont work!
<script>
//js to php - variable pass
var a = 'abc';
< ?php
$b='document.write(a)';
//echo $b;
?>
</script>
< ?php
echo $b;
?>
Here you’re generating the script via PHP. But, our goal is to carry the value ‘abc’ to a PHP variable.
PHP variable ‘b’ wont get the value of JavaScript variable ‘a’ without a page load because JS is client side and PHP is server side 🙂
Is there a way to pass variable from ajax called within a separate js file (not inline script) back to the js file? I’d prefer not to call it within the index.php file
Hi Jerry,
Is this what you want?
This is your external js file. Include it with
<script src="script.js" type="text/javascript"></script>
and code of script.js is below.
Thank you so much, Arpan. This is helpful.
What about the opposite direction? Where my js file makes an ajax call and then gets back some variable from the ajax, which can then be manpulated by the js.
For example, in the code below, I want a person to use a form to add a row to database. After running the php script, it should send back the AUTO INCREMENT id value of the new row. Then I want to save that value to a javascript variable so I can use it elsewhere.
When I declare and define that variable within the complete method, it seems I can only manipulate that var within the complete method and can not use it globally.
function createRow() {
$.ajax({
type:’POST’,
url:’createRow.php’,
data:$(‘#eventInputForm’).serialize(),
error: function () {
$(‘#output’).append(‘Error!’);
},
complete: function (response) {
$(‘#output’).html(“The ID of the new event is: ” + response.responseText);
},
});
$(“#output”).css({backgroundColor: “red”});
return false;
};
Hmm… Try the code below. I made the ajax response data global (global_data).
This is great. Thank you so much for the help.
You’re welcome Jerry 😉
I have a problem which i cannot solve.
I have this php code that if i click a checkbox it asks JS to check if the box is checked or not.
than i want the answer to carry back to php and following the result to do some action.
currently each time i click it reloads the site and so the answer is not saved.
Do you know the best way to do it?
My code at the moment-
var office = false;
function validate_c5()
{
if (document.getElementById(“c5”).checked)
{
office = true;
window.location = “”;
}
else
{
office = false;
window.location = “”;
}
}
If you click on a check box, it’ll check it if not-checked and vice-versa and then the code below return the updated result to you. Whats the point of checking then?
After this you can send the returned data to php via URL (GET method).
If you do not want a reload, use the AJAX method.
Hello!
Thank you very much for the tutorial. I am using the 3rd part and is working reat: “Pass variable from JavaScript to PHP without reloading the page using AJAX”
But now, I want to pass a json from Javascript to PHP without reloading the page.
Is this possible with your code?
I have tried to this:
How can I pass a json object without reloading the page? Can I adapt your script?
Thank you
Hello Pavelescu,
Why don’t you send (using post method) the json data as text string and then process it in php?
Hello again, I don’t really know what you mean / how to do this. Could you show me please?
I mean like this
Instead of
Hello.
I have replaced everything from my js with the what you said above:
// js
var jsonString = answer;
document.getElementById(“link”).onclick = function () {
// ajax start
var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers
else xhr = new ActiveXObject(“Microsoft.XMLHTTP”); // for IE
var url = ‘process.php?json_var=’ + jsonString;
xhr.open(‘POST’, url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState===4 && xhr.status===200) {
var div = document.getElementById(‘update’);
div.innerHTML = xhr.responseText;
}
}
xhr.send();
// ajax stop
return false;
}
// php
// receive the data using $_POST[‘json_var’]
// then use json_decode function of php (http://php.net/json_decode)
Also, my process.php looks like that:
<?php
if (isset($_POST['json_var'])) $php_var = $_POST['json_var'];
else $php_var = "json_var is not set!”;
$data = json_decode($php_var, true);
print_r($data);
?>
Nothing is displayed on the index.php page (where the js is), it is setup properly, I have this in the body:
Click me to put here the JSON string!
http://pavelescurazvan.eu/test_j/book/ this is the index.php page
http://pavelescurazvan.eu/test_j/book/process.php thats the process.php
Can you help me out again?
Thanks!
I have modified the process.php and it outputs “json_var is not set!”. Why is this happening?
this is the new process.php:
if (isset($_POST['json_var'])) $php_var = $_POST['json_var'];
else {
$php_var = "json_var is not set!";
echo $php_var;
}
$data = json_decode($php_var, true);
print_r($data);
Sorry, my mistake, I forgot that we are using POST method. So, there will be some changes.
Here is the new script with working post method
process.php
I replaced POST with GET everywhere and it works :). Why is not working with POST?
Because I forgot that we are using POST method 😛 !
I recommend you to use POST method as POST has no size limitations as you’re sending json data.
For post method, we need to use setRequestHeader additionally and our variable goes through as parameter of send.
Hope, this script worked for you.
Hello Arpan.
Thanks a lot!
Working great with your json example. If I pass a much bigger json variable (the one I am displaying in the index.php) in the script, nothing is showed again. Is it possible this variable to be too big? Or what could be?
This is the link, it would be even more awesome if you could toss an eye on my javascript:
http://pavelescurazvan.eu/test_j/book/
Cheers,
Razvan
Hi,
If your string has line breaks, it will break your script. To fix that just add backslash (“\”) on the line breaks.
Like this
No, variable size will not be matter as we’re using POST method. Thats why I suggested you POST.
Morning! Well this json has linebreacks but I cant do nothing about it. isnt there any solution? I am reciving this json from an api, I dont have control over it. But still, in the console the json doesnt have line breaks. What should I do?
What I found that ajax send or post has limitations (by browser or webserver).
Its about 1275 characters (bytes).
By the way, What do you want achieve and what things do you have? Tell me from first.
There might be a inappropriate logic which can lead you into huge nasty codes.
with other words you cant send big jsons.. thats awfull. Can you recommand me another way to pass a json from javascript to php? I have to insert this json into the database, and I dont know another way but with php..
I have to insert this json from the javascript into a mysql DB, this is why I wanted to pass it as a variable from JavaScript to PHP. What do you suggest?
Hello again,
Sorry, I was busy.
Why don’t you send the URL of the JSON file to the process.php?
I think is a problem with my json format, I tried to hardcord attach it, but still is not working.
Look, this is my json copied into a file: http://pavelescurazvan.eu/test_j/book/myjson.txt
thanks,
Razvan
How can i use this script (js to php) use with vector map to select seats for an event and store in database (booked seats)??
Hello SD,
Pardon me, but I could not find any link between my script and what you’re saying.
Please be more specific about what you want to do and how you’re relating your problem with my script.
Thank you.
Hi Arpan,
First of all thanks for sharing below three methods. They are very useful to me as I am new in the Cyber space.
1. Pass variable from PHP to JavaScript
2. Pass variable from JavaScript to PHP
3. Pass variable from JavaScript to PHP without reloading the page using AJAX
I have used or rather modified the first method to pass variable from PHP to HTML form input (i.e. initial value). The value comes from the SQLite database via PHP access. Basically it displays the current value in the SQLite database as an initial value for the form input when the page is loaded or reload.
I have also used or rather modified your second method to pass variable from HTML form input to PHP. The PHP is then using the variable to modify the SQLite content. It works fine and as what you have pointed out the page would be reloaded. However noticed that the input of the form always stays with what has been keyed in previously and is not displaying the updated (by other application) value of the SQLite database with re-loading.
Basically what I want to achieve is that the input of the form always display the current database value when the page is loaded or reloaded. The user could key in the input form and change the database value where the content could also be modified by other application as well.
Thanks & regards,
Kim Lee
I am trying to pass the window.innerWidth from my html to a php script. I’ve tried to use replies modified from previous posts. My code is MVC. I initialize with the init.php controller which contains the following code, which gets the window.innerwidth. I want to pass the result to the home controller. I don’t want to use a link because I don’t want any interaction from the user.
Earlier tests has had ajax send to init.php, which I’ve tried to trap. init.php looks like this:
This does get me to init.html, which has this code:
If it worked, it would go to home.php, the home controller, which looks like this:
The result I get looks like this:
I hope this tells you what you need to know to help me. Thanks.
Hi Alan,
Sorry for late reply, I was very busy.
Why don’t you use $_SESSION to store the result?
Hi! How would this work with multiple variables? What i am trying to do is something like this: ( Do note that its probably not correct, because it does not work…
This is the 3 variables that i need to send to the php file:
var url = ‘commentcreate.php?post_id=’ + post_id + ‘&user_id=’ + user_id + ‘&comment=’ + comment
And this is how i would “recieve” it:
if(isset($_GET[‘post_id’]) && isset($_GET[‘user_id’]) && isset($_GET[‘comment’])) $post_id = $_GET[‘post_id’] && $user_id = $_GET[‘user_id’] && $comment = $_GET[‘comment’];
Any idea what i did wrong and or how i can get it to work?
Well i found out what it was. A stupid mistake by me. Its supposed to be:
if(isset($_GET[‘post_id’]) && isset($_GET[‘user_id’]) && isset($_GET[‘comment’])) {
$post_id = $_GET[‘post_id’];
$user_id = $_GET[‘user_id’];
$comment = $_GET[‘comment’];
Incase anyone was wondering…
Please look at the below code
<a href="javascript:showpopup()” id=”lnkdetail”>Popup
my JS code is as under
function showpopup(uid)
{
var JSuid=uid;
alert(JSuid);
}
What i want is that, when i click on the link, it gets the ID using PHP, and throw is into uid argument.
in the function, the javascript exchange the uid value with PHP, and then the SQL query start to get the data from the table and show it as an alert. But this code is not working. Please help
MISSING PHP CODE. Trying to place PHP code in quotes
”
function showpopup(uid)
{
// alert(uid);
var JSuid=uid;
alert(JSuid);
}
“
Use the last method (Pass variable from JavaScript to PHP without reloading the page using AJAX).
Problem with placing codes? Upload your code to dropbox and link it here.
Hi, I can’t seem to run javascript codes inside process.php
hi,
what are you getting within $_GET[‘js_var’] in process.php?
Hi,
What are the errors? Or, what do you think that not seems working to you?
I just want to thank you very much!I searched a lot for this and you supplied working and understandable code that I can use and experiment on. I am making a site, something like mini-Instagram for a project and I wanted to have an upvote button that would connect with the database and update the number of likes and the users that have liked the picture and the 3rd example you gave did the job for me.Thank you again.
You’re most welcome…
Hi Arpan,
Thanks a lot for your post.
I am an instructional designer and used your method for a short sample.
http://blog.kawstov.com/storyline-to-php-via-ajax/
I created this a long time back and almost forgot about it, till I found some issue and had to refer your post again.
how we get selected select box value in same php page without refresh or without button click event.
it handle on selectbox value change event.
Great tutorial. This tutorial was really useful to how to pass the variable form PHP to JavaScript and java-script to PHP without page reloading. Thanks.
Hi, how to send the value of the id of the images being loaded from the DB to another php page. The images are loading dynamically and the id should pass only when the image or a button on the image is clicked.
Can you please help?
Thank You!!
dear Arpan Das,
how can possible to jquery variable value pass to PHP variable?
for example
$(document).ready(function(){
$(‘.asc’).on(‘click’,function(){
var gtotalPrice=$(this).attr(‘data-id’);
var grandpriceElement=$(“.”+gtotalPrice);
var value=grandpriceElement.html();
var qElement= $(this).attr(‘data-q’);//.val();
var q=$(“#”+qElement).val();
var subElement=$(this).attr(‘data-sub’);//.html();
var sub=$(“.”+subElement).html();
if (q>=0){
var total= q*sub;
grandpriceElement.html(total);
}
})
});
that script code working fine. so i want to ” var total” value pass in the below PHP code in “$total_price += total;”
if possible please give me any solution to that problem.
Hi umair,
Check this section of this post: “Pass variable from JavaScript to PHP without reloading the page using AJAX”.
Then replace JavaScript code with your jQuery code, the logic is same.