javascriptphphtmlcssajax

Ajax live search is not working after searching one value


my page requires refreshing the page after every search. please any help. I am bignner for Ajax and here is my index page code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){

    $("#live_search").keyup(function(){
      var input = $(this).val();
      //alert(input);

      if(input != ""){
        $.ajax({

          url:"livesearch.php",
          method:"POST",
          data:{input:input},

          success:function(data){
           $("#searchresult").html(data);
          }
        });
      }else{
        $("#searchresult").css("display", "none"); 
      }
    });
  });
    
</script>

and here is my php code

<?php

include('our/db_connect.php');

if(isset($_POST['input'])){

$input = $_POST['input'];
$query = "SELECT * FROM parcels WHERE reference_number LIKE '{$input}'";
$result = mysqli_query($conn, $query);

if(mysqli_num_rows($result) > 0){?>

        <table class="table table-bordered table-striped mt-4">
            <thead>
                <tr>
                    <th>tracking num</th>
                    <th>sender contact</th>
                    <th>status</th>
                    <th>From</th>
                    <th>To</th>
                </tr>
            </thead>
            <tbody>
                <?php
                while($row = mysqli_fetch_assoc($result)){
                    $ref = $row['reference_number'];
                    $sender = $row['sender_name'];
                    $from = $row['from_branch_id'];
                    $to = $row['to_branch_id'];

                    ?>
                    <tr>
                        <td><?php echo $ref;?></td>
                        <td><?php echo $sender;?></td>
                        <td><?php echo $from;?></td>
                        <td><?php echo $to;?></td>
                    </tr>

                    <?php
                }
                

?>

            </tbody>
        </table>
    <?php 
    
}else{
    echo "No Parcel Found";
}

} ?>


Solution

  • You're hiding the div but not showing it again when you have ajax result.

    Write the ajax code like:

    if (input != '') {
        $.ajax({
            url: 'livesearch.php',
            method: 'POST',
            data: { input: input },
            success: function (data) {
                $('#searchresult').html(data);
                $('#searchresult').show();
            },
        });
    } else {
        $('#searchresult').hide();
    }
    

    Here I am showing the $('#searchresult') again after your have response and you replaced the HTML in $('#searchresult')