0

I have an AJAX function which populates a table as the user searches. Each keyup provides new results based on their search criteria.

I want to validate the search to keep users from excessively triggering the event which obviously could cause tons of problems. But I do need the functionality of the list repopulating as the user searches or types.

How can I provide validation to protect the server and make the code overall more professional.

AJAX var searchPath = "";

$("#itemID").keyup(function (){
    var url = searchPath;
    $.ajax({
        type  : "POST",
        async : false,
        url   : url,
        data: $('#itemID').serialize(),
        cache : false,
        success: function(html) {
           $( "#productResults" ).html( html );
        if (html === null) {
                  $("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
              } else {
                  $("#loader_message").html('These are your search results... <img src="../wp-content/uploads/2016/02/loading.gif" alt="Loading">').show();
              }
        if( !$('#itemID').val() ) {                     
                displayRecords(limit, offset);   
            }
                html = null;
                window.busy = false;
            }
      });
});   

FORM

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

CONTENT AREA

<tbody id="productResults"> 

                </tbody>

            </table>
<div id="loader_image"></div>
<div id="loader_message"></div>
wuno
  • 9,547
  • 19
  • 96
  • 180
  • What I've done is just add a timer that fires off an ajax request after typing has stopped for a second. That way it doesn't pound the server. As long as your inputs are sanitized, you should be OK. – Paul Carlton Feb 16 '16 at 20:24
  • Hey thanks! Would you mind showing me how you would do that? – wuno Feb 16 '16 at 20:25
  • Look at "debounce" or "throttle" – epascarello Feb 16 '16 at 20:33
  • I made something that would trigger a keyup if the TIMEOUT was met from a setInterval function and the keyup would trigger it's initial set. It was a quick jquery plugin that I never maintained really. If I had to do something like that again, I would probably look into epascarello's suggestions instead of rewriting it especially if I was on a time crunch. – Paul Carlton Feb 16 '16 at 20:59
  • This should help you: http://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery – axel.michel Feb 16 '16 at 21:41

0 Answers0