Categories
javascript php variables

How do I pass JavaScript variables to PHP?

172

I want to pass JavaScript variables to PHP using a hidden input in a form.

But I can’t get the value of $_POST['hidden1'] into $salarieid. Is there something wrong?

Here is the code:

<script type="text/javascript">
    // View what the user has chosen
    function func_load3(name) {
        var oForm = document.forms["myform"];
        var oSelectBox = oForm.select3;
        var iChoice = oSelectBox.selectedIndex;
        //alert("You have chosen: " + oSelectBox.options[iChoice].text);
        //document.write(oSelectBox.options[iChoice].text);
        var sa = oSelectBox.options[iChoice].text;
        document.getElementById("hidden1").value = sa;
    }
</script>

<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
    <input type="hidden" name="hidden1" id="hidden1" />
</form>

<?php
   $salarieid = $_POST['hidden1'];
   $query = "select * from salarie where salarieid = ".$salarieid;
   echo $query;
   $result = mysql_query($query);
?>

<table>
   Code for displaying the query result.
</table>

2

  • 2

    You can store the js variable value in a cookie and later access that variable in php cookie.

    Sep 20, 2013 at 2:45


  • 3

    @shasikanth – you can do that, but the cookie won’t be set until the second time the page is viewed. And at that time, it will be the value from the first page view – it is always one behind. A cookie is not a mechanism to dynamically pass info back to server; you have to do something else to refresh the page, e.g. POST a form, or make an Ajax call. And if you are doing one of those, there is no reason to use a cookie – just pass the info in the mechanism you are using. Also, a cookie will persist after the page is gone – not what is intended in this question.

    Oct 16, 2019 at 9:08

115

+50

You cannot pass variable values from the current page JavaScript code to the current page PHP code… PHP code runs at the server side, and it doesn’t know anything about what is going on on the client side.

You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.

<DOCTYPE html>
<html>
  <head>
    <title>My Test Form</title>
  </head>

  <body>
    <form method="POST">
      <p>Please, choose the salary id to proceed result:</p>
      <p>
        <label for="salarieids">SalarieID:</label>
        <?php
          $query = "SELECT * FROM salarie";
          $result = mysql_query($query);
          if ($result) :
        ?>
        <select id="salarieids" name="salarieid">
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
            }
          ?>
        </select>
        <?php endif ?>
      </p>
      <p>
        <input type="submit" value="Sumbit my choice"/>
      </p>
    </form>

    <?php if isset($_POST['salaried']) : ?>
      <?php
        $query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
        $result = mysql_query($query);
        if ($result) :
      ?>
        <table>
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<tr>';
              echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
              echo '</tr>';
            }
          ?>
        </table>
      <?php endif?>
    <?php endif ?>
  </body>
</html>

8

  • @Sergey, I have used submitting form here with POST method, i don’t know why it doesn’t work. Do you know why? And how to solve that?

    Dec 17, 2009 at 10:14

  • @sergey, so i need to use ajax? Actually, i’m familliar with that.

    Dec 18, 2009 at 10:08

  • Actually, I have used your method in the past one level select box. But now i have made a three-chained select box, so i can’t use your method.

    Dec 18, 2009 at 10:17

  • At this point: Yes, you need to use AJAX technology. If you have troubles with realization, I think I can help.

    Dec 18, 2009 at 17:50

  • 3

    @MadaraUchiha The OP already used mysql_ functions; it wouldn’t be the goal of answering this question with a complete rewrite.

    – Ja͢ck

    Oct 17, 2012 at 4:14

38

Just save it in a cookie:

$(document).ready(function () {
  createCookie("height", $(window).height(), "10");
});

function createCookie(name, value, days) {
  var expires;
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
  }
  else {
    expires = "";
  }
  document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}

And then read it with PHP:

<?PHP
   $_COOKIE["height"];
?>

It’s not a pretty solution, but it works.

5

  • 3

    Finaly! a selution that works! I’ve been looking for hours for a selution now, making a game and would like to send the highest score to a database, got it fixed now! Cheers!

    – Cid-El

    Nov 15, 2016 at 8:16

  • 1

    actually, its a great solution! going from php to javascript is easy. from javascript to php is not easy. using a cookie is simple, elegant. no bs..!! of course if the client turns off cookies,,,thats an issue to handle with a default..

    – JamesAD-0

    Jul 15, 2017 at 18:04


  • Can you please let me know how to use the $_COOKIE[“height”] thing to get the name, value in it? Thanks. Not working for me.

    – Zac

    Aug 5, 2017 at 6:40


  • 10

    Despite all the upvotes, this is not a good solution. Reason: the cookie isn’t seen by the server until the next time the page is requested by the browser. Its always “one behind”. The first time the page is opened in browser, there won’t be any cookie at all. Is this acceptable? The next time the page is opened in browser, there will be a cookie from the first time. For a constant value, such as this example, that might be tolerable (despite not working the first time!!). Now consider a dynamic value, such as current datetime. php will be seeing PREVIOUS datetime, not now. Use ajax.

    Oct 16, 2019 at 8:52


  • I get errror Undefined index: height

    Nov 8, 2020 at 8:04

21

There are several ways of passing variables from JavaScript to PHP (not the current page, of course).

You could:

  1. Send the information in a form as stated here (will result in a page refresh)
  2. Pass it in Ajax (several posts are on here about that) (without a page refresh)
  3. Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:

 if (window.XMLHttpRequest){
     xmlhttp = new XMLHttpRequest();
 }

else{
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }

 var PageToSendTo = "nowitworks.php?";
 var MyVariable = "variableData";
 var VariablePlaceholder = "variableName=";
 var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;

 xmlhttp.open("GET", UrlToSend, false);
 xmlhttp.send();

I’m sure this could be made to look fancier and loop through all the variables and whatnot – but I’ve kept it basic as to make it easier to understand for the novices.

2

  • how about how will i get the db arrays and pass it on the javascript everytime i submit a new form. then the variable in javascript will also change. how? help me. 🙁

    – Vincent

    Nov 2, 2013 at 1:40

  • 3

    Ajax is actually XMLHttpRequest, the latter is just a technical term for it.

    – Alex C.

    Jul 6, 2016 at 22:09