Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass JavaScript variables to PHP?

People also ask

Can we assign JavaScript variable to PHP variable?

Javascript will be interpreted in Client's browser and you can not assign it to PHP variable which is interpreted on SERVER .

Can you put JavaScript code in PHP?

You can execute Javascript through PHP by calling javascript code/function as a string in PHP and send it to the client browser to execute.

Can PHP interact with JavaScript?

Answer : PHP and Javascript cannot directly interact since PHP is a server side language and Javascript is a client-side language. However, we can exchange variables since PHP can generate Javascript code to be executed by the browser and it is possible to pass specific variables back to PHP via the URL.


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>

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.


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.


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

when your page first loads the PHP code first run and set the complete layout of your webpage. after the page layout, it set 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. There is 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 interact Javascript with PHP without 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 load then you can use it with your Javascript example.

<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

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


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

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.