Note that there are some explanatory texts on larger screens.

plurals
  1. POTrying to add delay to jQuery AJAX request
    text
    copied!<p>I am trying to delay an AJAX request so that it is sent out 2-3 seconds after the LAST keyup of an input cell.<br> So far I have managed to delay the requests, but after 2-3 seconds I get one request sent for every keyup in the field...<br> How can I make jQuery cancel the first ones and just send the last keyup?<br> Here's the code so far: </p> <pre><code>$('#lastname').focus(function(){ $('.terms :input').val(""); //clears other search fields }).keyup(function(){ caps(this); //another function that capitalizes the field $type = $(this).attr("id"); // just passing the type of desired search to the php file setTimeout(function(){ // setting the delay for each keypress ajaxSearchRequest($type); //runs the ajax request }, 1000); }); </code></pre> <p>This code above, waits 1 sec then sends 4-5 AJAX requests depending on keypresses. I just want one sent after the last <code>keyup</code><br> I have found some similar solutions in StackOverflow that use Javascript, but I have not been able to implement them to my project due to my small knowledge of programming.</p> <p>[SOLVED] Final working code, thanks to @Dr.Molle:</p> <pre><code>$('#lastname').focus(function(){ $('.terms :input').val(""); }).keyup(function(){ caps(this); $type = $(this).attr("id"); window.timer=setTimeout(function(){ // setting the delay for each keypress ajaxSearchRequest($type); //runs the ajax request }, 3000); }).keydown(function(){clearTimeout(window.timer);}); </code></pre> <p>Here's the <code>ajaxSearchRequest</code> code:</p> <pre><code>function ajaxSearchRequest($type){ var ajaxRequest2; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest2 = new XMLHttpRequest(); }catch (e){ // Internet Explorer Browsers try{ ajaxRequest2 = new ActiveXObject("Msxml2.XMLHTTP"); }catch (e) { try{ ajaxRequest2 = new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){ // Something went wrong alert("Browser error!"); return false; } } } ajaxRequest2.onreadystatechange = function(){ if(ajaxRequest2.readyState == 4){ $result = ajaxRequest2.responseText; $('#resultcontainer').html($result); }} var searchterm = document.getElementById($type).value; var queryString ="?searchterm=" + searchterm +"&amp;type=" +$type; if(searchterm !== ""){ ajaxRequest2.open("GET", "searchrequest.php" + queryString, true); ajaxRequest2.send(null); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload