Ethan
Ethan

Reputation: 67

Ajax reset page to normal after search

I have a live search where it pulls all the relevant information from the database and displays it in the table relevant to the search using Ajax so it doesn't refresh the page, I have it so after each search it resets back to nothing until it receives another input but I want it to display what it normally does (all the information).

Before input is received: http://prntscr.com/hnmui8

After input is received: http://prntscr.com/hnmv0r

After input is removed: http://prntscr.com/hnmv53

What is want it to look like after inputs removed: http://prntscr.com/hnmvhr

index.php

    <!DOCTYPE html>
<html>
    <head>
        <title>Webslesson Tutorial | Autocomplete Textbox using Bootstrap Typehead with Ajax PHP</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    </head>
    <body>
        <br /><br />
        <div class="container" style="width:600px;">
        <h2 align="center">Ajax live data search using Jquery PHP MySql</h2>
        <div class="form-group">
            <div class="input-group">
                <span class="input-group-addon">Search</span>
                <input type="text" name="search_text" id="search_text" placeholder="Search by Customer Details" class="form-control" />
            </div>
        </div>
        <br />
        <div id="result">
            <div class='table-responsive'>
                <table class='table table-bordered'>
                <tr>
                    <th>Customer name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>Potal code</th>
                    <th>Country</th>
                </tr>
                <?php
                    include('db.php');
                    $customers = DB::query('SELECT * FROM live');
                    foreach($customers as $p){
                      echo '<tr>
                              <td>'.$p["name"].'</td>
                              <td>'.$p["address"].'</td>
                              <td>'.$p["city"].'</td>
                              <td>'.$p["postCode"].'</td>
                              <td>'.$p["country"].'</td>
                            </tr>';
                    }

                    ?>
            </div>
        </div>
    </body>
</html>
<script>
    $('#search_text').keyup(function(){
      var txt = $(this).val();
      if(txt != ''){
        $.ajax({
          url: "fetch.php",
          method: "POST",
          data:{search:txt},
          dataType: "text",
          success:function(data){
            $('#result').html(data);
          }
        });
      }else{
        $('#result').html('');
    });
</script>

fetch.php

<?php
$connect = mysqli_connect("localhost", "root", "", "ajax");
$output = '';
$sql = "SELECT * FROM live WHERE name LIKE '%".$_POST['search']."%'";
$result = mysqli_query($connect, $sql);

if(mysqli_num_rows($result) > 0){
  $output .= "<h4 align='center'>Search result</h4>";
  $output .= "<div class='table-responsive'>
                <table class='table table-bordered'>
                  <tr>
                    <th>Customer name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>Potal code</th>
                    <th>Country</th>
                  </tr>";

 while($row = mysqli_fetch_array($result)){
   $output .= '
               <tr>
                <td>'.$row["name"].'</td>
                <td>'.$row["address"].'</td>
                <td>'.$row["city"].'</td>
                <td>'.$row["postCode"].'</td>
                <td>'.$row["country"].'</td>
               </tr>
              ';
 }
 echo $output;
}else{
  echo "There are no customers.";
}

?>

Thanks, Ethan

Upvotes: 3

Views: 1121

Answers (2)

Tuğca Eker
Tuğca Eker

Reputation: 1493

Last Update: I (lately) realized that your JS code already have an empty string check (thanks to @Taplar). @dferenc already posted correct answer for your case. But still if you want to be sure that your list is "fresh" you can follow my solution.

When you send an empty string to the server as a value of the parameter, it may be ommited. So, you should add a conditional check for that.

Use

$queryWord = isset($_POST['search']) ? $_POST['search'] : '';
$sql = "SELECT * FROM live WHERE name LIKE '%".$queryWord."%'";

or (after PHP7, you can use null coalescing operator)

$queryWord =  $_POST['search'] ?? '';
$sql = "SELECT * FROM live WHERE name LIKE '%".$queryWord."%'";

instead of

$sql = "SELECT * FROM live WHERE name LIKE '%".$_POST['search']."%'";

Important Note: Beware of SQL Injections always! Protect your code against injections. You may start from here.

Important Note 2: I suggest you to use "Developer Console" feature of browsers. All commonly-used browsers have inline-tool for developers to debug, trace network requests and do some magic.

Upvotes: 1

dferenc
dferenc

Reputation: 8126

You could save your original dataset into a variable and if the input is '', than instead of setting the html content to '', you could restore the content from the variable like so:

var originalData = $('#result').html();
$('#search_text').keyup(function(){
  var txt = $(this).val();
  if(txt != ''){
    $.ajax({
      url: "fetch.php",
      method: "POST",
      data:{search:txt},
      dataType: "text",
      success:function(data){
        $('#result').html(data);
      }
    });
  } else {
    $('#result').html(originalData);
  }
});

Upvotes: 4

Related Questions