Skip to content
Advertisement

How to retrieve the results from an AJAX search?

I’m trying to figure out how to send the results from an AJAX search but it does not work. I want to return the results back to the website after searching, I think my problem comes from the SQL query but I can’t figure it out.

This is my php code:

<?php
include('db_conn.php');

$output="";

  $search = mysqli_real_escape_string($mysqli,$_POST["search_text"]);
  $query = "SELECT * FROM unit
  WHERE id LIKE '%$search%'
  OR unit_code LIKE '%$search%'
  OR unit_name LIKE '%$search%'
  OR lecturer LIKE '%$search%'
  OR semester LIKE '%$search%'
  ";
$result = mysqli_query($mysqli,$query);
if(mysqli_num_rows($result) > 0){
  $output .='<div class="table-responsive">
   <table class="table table bordered">
    <tr>
     <th>ID</th>
     <th>Unit Code</th>
     <th>Unit Name</th>
     <th>Lecturer</th>
     <th>Semester</th>
    </tr>
       ';
  while($row = mysqli_fetch_array($result)){
    $output.='
       <td>'.$row["id"].'</td>
       <td>'.$row["unit_code"].'</td>
       <td>'.$row["unit_name"].'</td>
       <td>'.$row["lecturer"].'</td>
       <td>'.$row["semester"].'</td>
    </tr>
    ';
  }
  echo $output;
}
else {
  echo 'Error php';
}

 ?>

And this is the ajax:

   <script type="text/javascript">
        $('#search_button').click(function(){
          var keywords = $('#search_text').val().trim();
          $.get("search.php",
                {keywords:keywords}).done(function(data){
                  alert('test');
                  $('#result').html(data);
                });
        });
       </script>

Advertisement

Answer

I believe your problem is that you are using $.get, but you are attempting to retrieve the value in your PHP from the $_POST variable which would have nothing in it, it would be in the $_GET variable.

I suggest you change your ajax call to use $.ajax

<script type="text/javascript">
  $('#search_button').click(function(){
    var keywords = $('#search_text').val().trim();
    $.ajax({
      url: "search.php",
      data: {search_text: keywords},
      method: 'POST',
      success:function(data){
        $('#result').html(data);
      },
  });
</script>

The first key in the data array should match the key you use in PHP to collect the value from $_POST

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement