简体   繁体   中英

AJAX On Keyup Search Function

I wrote a AJAX search function which grabs the keyword values on key up and fires off the script. My goal is to have it populate the content area every key reordering the results to be in ABC order.

Instead what's happening is the first key fires off and the top result is always this

*ENGRAVING

then the rest of the values under it are in no specific order that I can tell.

I think this has to do with escaping characters?

Any help would be appreciated. Please help me get this to function so as a user searches the content area reorders itself being in order based on the keyword being searched up to the value that has been entered at that time.

On page load 5 results are added to the page then on page scroll more results are added to the page like this,

var assetPath = "<?php echo $assetPath ?>";
var searchPath = "<?php echo $searchPath ?>"; 

function displayRecords(lim, off) {
  jQuery.ajax({
          type: "GET",
          async: false,
          url: assetPath,
          data: "limit=" + lim + "&offset=" + off,
          cache: false,
          beforeSend: function() {
            $("#loader_message").html("").hide();
            $('#loader_image').show();
          },
          success: function(html) {
            $("#productResults").append(html);
            $('#loader_image').hide();
            if (html === "") {
             $("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show();
            } else {
             $("#loader_message").html('Loading... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
            }
            window.busy = false;
          }
        });
}

Then when a user wants to search they use this form,

<div class="form-group pull-right">
                    <input type="text" name="itemID" id="itemID" class="search form-control" placeholder="Search product number">
            </div>

Then this ajax function fires off on keyup

$("#itemID").keyup(function (){
    var itemID = $(this).val();
    var url = searchPath;
    $.ajax({
        type  : "GET",
        async : false,
        url   : url,
        data  : "itemID=" + encodeURIComponent(itemID),
        cache : false,
        success: function(html) {
              $('#loader_image').hide();
           $( "#productResults" ).replaceWith( html );

              if (html === "") {
                  $("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
              } else {
                  $("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
              }
              window.busy = false;
        }
      });
});    

which runs this script at searchPath as the path variable

require_once ('Dbconfig.php');
  $sql=" SELECT * FROM wuno_inventory WHERE wuno_product like '%".$itemID."%' OR wuno_alternates like '%".$itemID."%' ORDER BY wuno_product ";

  try {
  $stmt = $DB_con->prepare($sql);
  $stmt->execute();
  $results = $stmt->fetchAll();
} catch (Exception $ex) {
  echo $ex->getMessage();
}
if (count($results) > 0) {
  foreach ($results as $res) {
    echo '<tr class="invent">';  
    echo '<td>' . $res['wuno_product'] . '</td>';  
    echo '<td>' . $res['wuno_alternates'] . '</td>';  
    echo '<td>' . $res['wuno_description'] . '</td>';  
    echo '<td>' . $res['wuno_onhand'] . '</td>';  
    echo '<td>' . $res['wuno_condition'] . '</td>';  
    echo '</tr>';   
  }
}

The initial data populates perfectly in order from what is in the database. So I do not see why there would be problems for this function if it is a escaping situation.

Also the initial data is paginated. Would this cause a problem with the second query? I was thinking maybe since there is so much data it's all being appended to the content instead of replacing it. Maybe the jquery is conflicting?

Try introducing the timeout for your AJAX call. Move your AJAX JS into a separate function first:

function get_search_results(event) {
    var itemID = $(event.target).val();
    var url = searchPath;
    $.ajax({
        type  : "GET",
        async : false,
        url   : url,
        data  : "itemID=" + encodeURIComponent(itemID),
        cache : false,
        success: function(html) {
              $('#loader_image').hide();
           $( "#productResults" ).replaceWith( html );

              if (html === "") {
                  $("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
              } else {
                  $("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
              }
              window.busy = false;
        }
      });
}

Then add it to your keyup handler:

$("#itemID").keyup(function (){
    setTimeout(get_search_results, 200);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM