-1

I want to pass Javascript variable to PHP, but it is never set. I have everything in one .php file

CODE:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="asd.css">
    <title>Tabulka</title>
</head>
<body>

<script>
$(document).ready(function(){
    $("#table tr").click(function(){
       $(this).addClass('selected').siblings().removeClass('selected'); 

       var value = $("#table tr.selected td:first").html();

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "tabulka.php?id=" + value, true);
        xmlhttp.send();
    });
});
</script>
<table id="table">  
    <tr>
        <th>A</th> <th>A</th> <th>B</th> <th>C</th> <th>D</th>
    </tr>

    <tr>
        <td>51</td> <td>41</td> <td>1515</td>  <td>419</td>    <td>asd</td>
    </tr>

    <tr>
        <td>52</td> <td>41</td> <td>1515</td>  <td>419</td>    <td>asd</td>
    </tr>

    <tr>
        <td>63</td> <td>41</td> <td>1515</td>  <td>419</td>    <td>asd</td>
    </tr>
</table>

<form method="POST">
    <input type="submit" name="ok-submit" class="ok" value="OKOK">
</form>
</body>
</html>


<?php 
if(isset($_REQUEST['id'])){
    echo $_REQUEST['id'];
}
?>

I am using XMLHttpRequest to pass variable. It works like If I click on table row. First td is pass to php variable and print it out the print it out. But he $_REQUEST['id'] is never set.

2 Answers2

0

You can't pass variable values from the current page Javascript to the current page PHP code ... PHP code runs at the server 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>
0

It is possible to pass data via javascript to another page to be handled server side by PHP, build a result and then display it on the current page where the javascript resides. It is pretty slick and won't require a page refresh or a form to be submitted.

My example below is a simple lookup function. User enters a query string and hits search. The contents of the text box is passed to a javascript function, its passed off to a PHP page that runs a database query (or does whatever you want), builds some HTML and then outputs that HTML on the current page the user is on. In this case it will dump it as innerHTML within this div:

 <div id='studentResults'></div>

Here is the HTML:

<div id='quickStudentLookup'>
        <div>
            <p>Quick Search</p>
        </div>

        <div>
            <input id='queryString' name='queryString' type='text' placeholder='First OR Last Name' />
            <input type='submit' value='Search' onclick="javascript:ajax_post();" />

        <div id='studentResults'></div>
        </div>
    </div>

Javascript:

 function ajax_post(){
      // Create our XMLHttpRequest object
      var hr = new XMLHttpRequest();

      var url = "studentSearch.php";  // this is a file that would take the queryString, perform something on it and echo some HTML back.  The HTML will end up as innerHTML of the div id studentResults

      // Create some variables we need to send to our PHP file  
      var queryString = document.getElementById("queryString").value;
      var vars = "queryString="+queryString;
      hr.open("POST", url, true);

      // Set content type header information for sending url encoded variables in the request
      hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      // Access the onreadystatechange event for the XMLHttpRequest object
      hr.onreadystatechange = function() {

           if(hr.readyState == 4 && hr.status == 200) {
                var return_data = hr.responseText;
                document.getElementById("studentResults").innerHTML = return_data;
           }
           else{

           }
      }
      // Send the data to PHP now... and wait for response to update the status div
      hr.send(vars); // Actually execute the request
 }

PHP: This can be whatever you want. Here is a simple example that takes the data, queries a database and echos a result. The echo will happen within the DIV with ID studentResults. This is defined in the JS above.

 <?php 
      // database connection omitted
      $queryString = $_POST['queryString']; // get var from post

      $studentSearch = "SELECT
      student.student_id,
      student.firstName,
      student.lastName,
      student.studentID
      FROM
      student
      WHERE student.lastName = :queryString
      LIMIT 10"; // build query

      $sth = $handler->prepare($studentSearch); // pdo to run query
      $sth->execute(array(':queryString'=>$queryString));
      $results = $sth->fetchAll();                  

      foreach($results as $r){  // loop through results and output
          $firstName        = $r['firstName'];
          $lastName         = $r['lastName'];
          $studentID        = $r['studentID'];

          echo "<p>$firstName $lastName - $studentID</p>";

      }

 ?>

Hope it helps!