James
James

Reputation: 16349

Datatable global search throwing occasional ajax error

I have a 2 pages with 3 and 4 datatables on them respectively.

I have a requirement to replace the default search box for each datatable with one global search box.

So far I have implemented this just fine, I have the global search box set and hide the individual search boxes like so:

//Other JS to initialise datatables with Ajax serverside processing

$(".dataTables_filter").hide();

$("#datatable-search").keyup(function() {
    $(".dataTable").DataTable().search($(this).val()).draw();
});

The datatables are using ajax calls to load information serverside.

When it was just one datatable, I didn't have this issue, but with the global search of all datatables I am getting the occasional ajax error - caused by a 500 error server side. Using the developer tools console, I can see which calls fail, but then I can open/run them just fine later.

The project uses Laravel and so checking the Laravel log, I see this:

[2017-11-06 00:03:50] production.ERROR: No application encryption key has been specified.

This would indicate that I haven't set the application key in my .env file - however, I have. The rest of my application works fine, heck even typing slowly works fine - it would appear the volume of calls causes this to happen, but I cannot understand why...

I can readily recreate the issue just by hitting backspace quickly a few times.

I could just redirect the error to the console, but I'd like to try and solve the error first. The error is currently just in my local environment and I haven't tried it in production yet - although I assume I will face a similar issue.

I considered disabling the text input until the search for the current keyup finishes, but this is quite invasive and not very UX friendly.

What would be the best way to go about this? Could there be a way to 'queue' up the ajax calls?

Upvotes: 4

Views: 473

Answers (1)

GramThanos
GramThanos

Reputation: 3622

Give some time to the user to type.

// Typing timeout
var typingTimeout = null;
// On keyup
$("#datatable-search").keyup(function() {
    // Clear previous timer
    clearTimeout(typingTimeout);
    // Set a new timer
    var that = this;
    typingTimeout = setTimeout(function(){
        $(".dataTable").DataTable().search($(that).val()).draw();
    }, 200); // Execute the search if user paused for 200 ms
});

Edit : Small error corrected.

Upvotes: 3

Related Questions