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!

Comments

  1. says

    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…….

    • says

      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

  2. Laia says

    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…

    • says

      Hi Laia,

      I showed three different methods:

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

      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

  3. David says

    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;
    }

    • says

      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:

    • says

      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 :)

  4. Jerry says

    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

    • says

      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.

  5. Jerry says

    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.

    • Jerry says

      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;
      };

      • says

        Hmm… Try the code below. I made the ajax response data global (global_data).

  6. says

    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 = “”;
    }
    }

    • says

      if i click a checkbox it asks JS to check if the box is checked or not.

      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.

  7. says

    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

    • says

      I mean like this

      Instead of

  8. says

    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!

  9. says

    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);

    • says

      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

    • says

      Because I forgot that we are using POST method :-P !
      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.

  10. says

    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

    • says

      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.

      • says

        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?

        • says

          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.

          • says

            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..

  11. says

    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)??

    • says

      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.

  12. Kim Lee says

    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

  13. says

    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.

    • says

      Hi Alan,
      Sorry for late reply, I was very busy.

      I don’t want to use a link because I don’t want any interaction from the user.

      Why don’t you use $_SESSION to store the result?

  14. Gabe M says

    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?

    • Gabe M says

      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…

Leave a Reply