How to pass JavaScript variables to PHP?

    |
  • Added:
  • |
  • In: Basic PHP

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 which the user has chosen function func_load3(name){ var oForm = document.forms["myform"]; var oSelectBox = oForm.select3; var iChoice = oSelectBox.selectedIndex; //alert("you have choosen: " + 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 display the query result. </table> 

Thanks for your advice.

This Question Has 12 Answeres | Orginal Question | Alex SUN

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.

Here's how I did it (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); 

You cannot pass variable values from the current page javascript 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 html-form using another mechanism, such as submitting form on 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> 

Yes, Its working for me.

<script> var p1 = "success"; </script> <?php echo "<script>document.writeln(p1);</script>"; ?> 

just save it in a cookie:

<script> $(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=/"; } </script> 

and then read it with php

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

its not a pretty solution, but it works. Cheers.

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']; } ?> 

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.

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 java 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 java script and the html you want and then to use the java script in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and java script 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 java script, 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.

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

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 on here about that) (without a page refresh)
  3. make a http request via a XMLHttpRequest request (without a page refresh) like this:
<script> 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(); </script> 

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.

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.

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>"; ?> 

Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

NEED HOSTING?
Are you searching for Good Quality hosting?
You can Try It!
Connect Social With PHPAns
Top