0

I am working on a project for school and it's about jQuery, PHP, symfony and all that web stuff :). It is actually my first time using jQuery and even though I have already learned something, there are still many thing I dont know how to solve.

In this project, one of the things I am supposed to make is basically filtering some results. I have a database and when the site is loaded, all items from the database are displayed in a table. Then above the table, there is a text field. When I type in it, the items in the table are filtered as I type. But sometimes, when I write for example "HP", the jQuery first finishes the request for "HP" and displays the result and then it finished the request for "H" and so it overwrites the result of "HP" and this shouldnt happen. If I make the requests synchronous, it prevents me from writing in the text field when a request is being processed. How can I make it so that the requests are completed in the order they were called?

The jQuery code of this part of the project looks like this:

var oldTerm;

function filter() {
var term = $('#term').val();
    //alert(term);
if(term != oldTerm) {
    $.ajax({
        url: url.replace('--', term).replace(/\/$/, '')
                    //musi bejt synchronni
    }).done(function(data) {
        $('#items_table tbody').html(data);
                    alert(term);
        // udalost se musi registrovat po nacteni radku!
        $('.edit_button').click(createForm);
    });
    oldTerm = term;
}
}

$(document).ready(function() {
oldTerm = null;
$('#term').keyup(filter);
});
Johhny-T
  • 27
  • 1
  • 3
  • 9
  • The first `A` in "AJAX" stands for **asynchronous** — order is specifically not guaranteed. The first thing is ... when we do filtering or typeahead-suggest we put a minimum character count on it; we never act on a single character ... and second, put a timeout on it; don't do your AJAX query/call until X milliseconds has elapsed since the last keystroke. (as long as the user is quickly typing no filtering is done; when they pause (1/10 second?) is when we issue the AJAX call.) – Stephen P Apr 03 '14 at 20:17

1 Answers1

0

I think your best shoot is to make a queue for the ajax call maybe use a lock too. You can also use this : Queue AJAX calls

Community
  • 1
  • 1
Su4p
  • 865
  • 10
  • 24