174

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. Commented 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. Commented Oct 16, 2019 at 9:08

16 Answers 16

118
+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? Commented Dec 17, 2009 at 10:14
  • @sergey, so i need to use ajax? Actually, i'm familliar with that. Commented 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. Commented 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. Commented 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
    Commented Oct 17, 2012 at 4:14
41

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
    Commented 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.. Commented 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
    Commented Aug 5, 2017 at 6:40
  • 16
    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. Commented Oct 16, 2019 at 8:52
  • I get errror Undefined index: height Commented Nov 8, 2020 at 8:04
23

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
    Commented Nov 2, 2013 at 1:40
  • 4
    Ajax is actually XMLHttpRequest, the latter is just a technical term for it.
    – Alex C.
    Commented Jul 6, 2016 at 22:09
16

Here is the Working example: Get javascript variable value on the same page in php.

<script>
var p1 = "success";
</script>

<?php
echo "<script>document.writeln(p1);</script>";
?>
5
  • 3
    I tried this consept then truly worked, but if I try like this: <?php var x =<script>document.writeln(p1);</script>"; ?>, then echo x; It doesn't worked. Do you have another way? Commented Oct 31, 2015 at 1:07
  • 6
    you can try like this <script> var p1 = "success"; </script> <?php $x = "<script>document.writeln(p1);</script>"; echo $x; ?> Commented Jun 20, 2016 at 7:59
  • 10
    The php in this case is simply echoing javascript to the page as a string. Javascript is not being passed to php.
    – Ben
    Commented Mar 9, 2018 at 6:47
  • Yes, that's what we need to do... sometimes we need to use JavaScript value in php on the same page & without refreshing the page... then it will work like charm.. :) Commented May 8, 2019 at 0:31
  • 4
    @ArslanTabassum No, you misunderstand the comment. php never sees the value of p1. echo "<script>document.writeln(p1);</script>"; uses the javascript variable p1 in javascript, not in php. document.writeln is a javascript function, which you are executing, in the browser, while browser is building the HTML page. Commented Oct 16, 2019 at 9:00
13

When your page first loads the PHP code first runs and sets the complete layout of your webpage. After the page layout, it sets the JavaScript load up.

Now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't - it needs to refresh the page. The only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP.

So, we use AJAX to get Javascript to interact with PHP without a page reload. AJAX can also be used as an API. One more thing if you have already declared the variable in PHP before the page loads then you can use it with your Javascript example.

<?php $myname= "syed ali";?>

    <script>
    var username = "<?php echo $myname;?>";
    alert(username);
    </script>

The above code is correct and it will work, but the code below is totally wrong and it will never work.

    <script>
    var username = "syed ali";
    var <?php $myname;?> = username;
    alert(myname);
    </script>

Pass value from JavaScript to PHP via AJAX

This is the most secure way to do it, because HTML content can be edited via developer tools and the user can manipulate the data. So, it is better to use AJAX if you want security over that variable. If you are a newbie to AJAX, please learn AJAX it is very simple.

The best and most secure way to pass JavaScript variable into PHP is via AJAX

Simple AJAX example

var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
    $.ajax({
            type: "POST",
            url: "YOUR PHP URL HERE",
            data:userdata, 
            success: function(data){
                console.log(data);
            }
            });

PASS value from JavaScript to PHP via hidden fields

Otherwise, you can create a hidden HTML input inside your form. like

<input type="hidden" id="mydata">

then via jQuery or javaScript pass the value to the hidden field. like

<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>

Now when you submit the form you can get the value in PHP.

1
  • 1
    Thank you. Very helpful. The jQuery method doesn't let you pass data that's generated as the page runs? You can't set an input field to a value & pick it up it up by php? This is one of the clearest Ajax examples I've seen. I'm looking forward to trying it.
    – curls
    Commented Sep 15, 2019 at 18:54
9

Here's how I did it (I needed to insert a local timezone into PHP:

<?php
    ob_start();
?>

<script type="text/javascript">

    var d = new Date();
    document.write(d.getTimezoneOffset());
</script>

<?php
    $offset = ob_get_clean();
    print_r($offset);
7

I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.

It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.

One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:

<img src="pic.php">

The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.

1
  • Effectively, we usually do this with Ajax requests from the JavaScript, which gives us the possibility to do a POST instead of a GET, meaning that you can send big things, such as files. But I like your idea of using an image with query parameters! I'll keep this idea in mind because it may be useful in some cases. And as you say, you can read the query parameters, the referrer and also some potential cookies, which could have been set by JavaScript, to transfer some JS data to the PHP code on the server. Commented Mar 28 at 7:57
6

PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.

If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.

Here's a previous question that you can follow for more information: Ajax Tutorial

Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.

<?php
if(isset($_POST))
{
  print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <input type="text" name="data" value="1" />
  <input type="submit" value="Submit" />
</form>

Clicking submit will submit the page, and print out the submitted data.

1
  • 1
    @Zurahn, yes, maybe i try to use XMLHttpRequest, so i can't pass javascript value to php script in the same page using javascript? I have searched a lot, someone says it can be done with hidden input in form. Do i need to try this solution furthur? Commented Dec 17, 2009 at 10:13
6

We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -

function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        FB.api('/me?fields=id,first_name,last_name,email', function (result) {
            document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
            console.log(document.cookie);
        });
    }
}

And I've accessed it (in any file) using -

<?php 
    if(isset($_COOKIE['fbdata'])) { 
        echo "welcome ".$_COOKIE['fbdata'];
    }
?>
4

Your code has a few things wrong with it.

  • You define a JavaScript function, func_load3(), but do not call it.
  • Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
  • Your form has no means to submit it. It needs a submit button.
  • You do not check whether your form has been submitted.

It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:

<?php
if (isset($_POST['hidden1'])) {
   echo "You submitted {$_POST['hidden1']}";
   die;
}

echo <<<HTML
   <form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
      <input type="submit" name="submit" value="Test this mess!" />
      <input type="hidden" name="hidden1" id="hidden1" />
   </form>

   <script type="text/javascript">
      document.getElementById("hidden1").value = "This is an example";
   </script>
HTML;
?>
3

You can use JQuery Ajax and POST method:

var obj;

                
$(document).ready(function(){
            $("#button1").click(function(){
                var username=$("#username").val();
                var password=$("#password").val();
  $.ajax({
    url: "addperson.php",
    type: "POST", 
    async: false,
    data: {
        username: username,
        password: password
    }
})
.done (function(data, textStatus, jqXHR) { 
    
   obj = JSON.parse(data);
   
})
.fail (function(jqXHR, textStatus, errorThrown) { 
    
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) { 
    
});
  
 
            });
        });

To take a response back from the php script JSON parse the the respone in .done() method. Here is the php script you can modify to your needs:

<?php
     $username1 = isset($_POST["username"]) ? $_POST["username"] : '';
    
     $password1 = isset($_POST["password"]) ? $_POST["password"] : '';

$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";

    ;  
    
    
   

if ($conn->query($sql) === TRUE) {
    
   echo json_encode(array('success' => 1));
} else{
    
    
  echo json_encode(array('success' => 0));
}





$conn->close();
?>
2

Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.

4
  • @perstilence, you're right, i didn't call the function. Do you know how to call it in php? Commented Dec 17, 2009 at 10:16
  • hmm. It looks like you want to call it when someone selects something in your form / an onClick handler. Calling it from PHP doesn't make any sense. Someone selects a form value, your function fires, updates a hidden form value, then makes its way to php on form post. No? Commented Dec 17, 2009 at 20:17
  • @pestilence, i want to let someone select an item in selectbox, and when i click submit button, a search result will be displayed in a table. So at the backend, when i choose the item, its value will be passed to an mysql query in php as a variable. This is what i want to do. But it seems i can't find the solution in javascript. Do you have any clue? Commented Dec 18, 2009 at 10:13
  • Yes, post or get method in the form will be accepted if it works. Commented Dec 18, 2009 at 10:15
2

May be you could use jquery serialize() method so that everything will be at one go.

var data=$('#myForm').serialize();

//this way you could get the hidden value as well in the server side.

1

This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.

Just set a cookie with the data you want to pass to PHP using javascript in the browser.

Then, simply read this cookie on the PHP side.

1
  • 1
    . . . would you like to give an example and maybe a relevant link or two? (See How to Answer.)
    – ashleedawg
    Commented Apr 3, 2019 at 20:19
-1

We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.

So it's better to use the AJAX to parse the JavaScript value into the php Code.

Or alternatively we can make this done with the help of COOKIES in our code.

Thanks & Cheers.

-1

Use the + sign to concatenate your javascript variable into your php function call.

 <script>
     var JSvar = "success";
     var JSnewVar = "<?=myphpFunction('" + JSvar + "');?>";
 </script>`

Notice the = sign is there twice.

2
  • Why this does not work when myphpFunction is, i.e. file_exists
    – Brethlosze
    Commented Apr 12, 2022 at 23:40
  • Call to undefined function myphpFunction() Commented Aug 19, 2022 at 22:40

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.