javascriptphpmysqlajaxjsgrid

jsGrid: How to pass additional variables from javascript to php using ajax


I'm using jsGrid for my project. View here for original source code

I want to pass an additional variable call $user_session to use for mysql select query in fetch.php but failed. Below is what i have been trying.

<script>

var user_session = "<?php echo $user_session; ?>"; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

//......

 controller: {
  loadData: function(){
   return $.ajax({
    type: "GET",
    url: "fetch_data.php",
    data: {user_session:user_session} //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   });
  },

 //......

Here's the fetch.php file

<?php

if($method == 'GET')
{
 $user_session = $_GET['user_session']; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

 $query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
 $statement = $connect->prepare($query);
 $statement->execute($user_session); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output[] = array(
   'id'    => $row['id'],   
   'first_name'  => $row['first_name'],
   'last_name'   => $row['last_name'],
   'age'    => $row['age'],
   'gender'   => $row['gender']
  );
 }
 header("Content-Type: application/json");
 echo json_encode($output);
}
//......
?>

What is the proper way to do this?


Solution

  • I'm able to do by this way.

    <script>
    
    //......
    
     controller: {
      loadData: function(filter){
        var user_session = "<?php echo $user_session; ?>"; //<<<<<<<<<<<<<<<<<<<<<<<<<<<
       return $.ajax({
        type: "GET",
        url: "fetch_data.php",
        data: {filter,
               user_session:user_session //<<<<<<<<<<<<<<<<<<<<<<<<<<<
              },
       });
      },
    
     //......
    </script>
    

    In fetch.php i do this.

    <?php
    
    if($method == 'GET')
    {
     $user_session = $_GET['user_session'];//<<<<<<<<<<<<<<<<<<<<<<<<<<<
    
     $query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
     $statement = $connect->prepare($query);
     $statement->execute([$user_session]); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
     $result = $statement->fetchAll();
     foreach($result as $row)
     {
      $output[] = array(
       'id'    => $row['id'],   
       'first_name'  => $row['first_name'],
       'last_name'   => $row['last_name'],
       'age'    => $row['age'],
       'gender'   => $row['gender']
      );
     }
     header("Content-Type: application/json");
     echo json_encode($output);
    }
    //......
    ?>
    

    For the security issue mentioned by @Andrea Golin, i will post another question.
    Thanks.