phpjqueryajaxmysqlilivesearch

Live Search with PHP and MySQL without page refresh


I'm trying to do a live search. I have an html page with a an input value. The input will take saleID's. Then I have a php file that connects to a MySQL database. I want to seach the database by sale ID's and update an html table based off of whats typed in the input. I have most of the code however, its saying nothing is been found.

First I'll give my HTML:=

<html>
<head>
<title></title>
<script src="jquery-1.11.1.js"></script>
<script>
$(document).ready(function ()
{
  load_data();

 function load_data(query)
{
 $.ajax({
 url:"test.php",
 method:"POST",
 data:{query:query},
 success:function(data)
 {
   $('#result').html(data);
 }
});
}

$('#saleID').keyup(function()
{
 var search = $(this).val();
 if(search != '')
 {
   load_data(search);
 }
 else
 {
   load_data();
 }
 });

});
  </script>
  </head>
  <body>
  </body>
  </html>
   <h1>Test</h1>
    <br>
    <br>

    <form>
     <p>Customer ID:</p>
    <input type="text" id="saleID" name="Sale">
    <br>
    <br>
    </form>
    <div id="result"></div>
    </body>
     </html>

Then here is my test.php file

 <?php
   header("Cache-Control: post-check=1, pre-check=2");
   header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");

    $choice = $_GET['qu'];
    $output = '';
    $con = mysqli_connect("localhost", "milkiewiczr520", "", "milkiewiczr520") or
    die("Failed to connect to database");

     $sql_command = "SELECT * FROM SALES WHERE CUSTOMERID = " . $choice . ";";

    $result = mysqli_query($con, $sql_command);

   if(mysqli_num_rows($result) > 0)
    {
     $output .= '
     <div>
      <table>
       <tr>
       <th>Sale ID</th>
       <th>Sale Date</th>
       <th>Customer ID</th>
       </tr>
       ';
     while($row = mysqli_fetch_array($result))
     {
       $output .= '
       <tr>
       <td>'.$row["SALEID"].'</td>
       <td>'.$row["SALEDATE"].'</td>
       <td>'.$row["CUSTOMERID"].'</td>
       </tr>
       ';
     }
      echo $output;
     }
    else
    {
       echo 'Data Not Found';
    }

    ?>

I am getting no data found.

Any ideas?


Solution

  • You are getting your data with $_GET while you send data as POST. Do this way to get your query :

        $choice = $_POST['query']; // the {query:query} parameter you declared in your ajax call
    

    (instead of : $choice = $_GET['qu'];)

    By the way, please try to use PDO to do safer requests.