I am attempting to follow the advice within this question to fit the following scenario:
On keyup, send an AJAX request to the server with the term in the input field. But if they continue to type, abort any existing AJAX requests so only one request is sent.
Here is my code as it stands:
jQuery(document).ready(function($) {
var $input = $('#s'),
inputVal = '',
inputCount = '';
function process_asr_request() {
$.ajax({
url: MyAjax.ajaxurl,
data: {
'action':'pondera_asr_request',
'inputVal' : inputVal
},
success:function(data) {
$('#search-results').append( data )
},
error: function(errorThrown){
console.log( errorThrown);
}
});
}
$input.on("keyup", function() {
// record the value of the input
inputVal = $input.val(),
// check the lenght on the value
inputCount = inputVal.length,
// define array for ajax requests
requests = [];
// Only process once there are 3 characters
if (inputCount > 2) {
// push ajax requests into the array
requests.push(
process_asr_request(i)
);
// loop through the array of requests
for(
var i = 0;
i < requests.length;
i++
)
// kill any queued requests
requests[i].abort();
};
});
});
I have two questions:
- Is this approach valid for what I am looking to achieve
- I get an "Uncaught TypeError: Cannot call method 'abort' of undefined" error with the above code. Where am I going wrong.
I'm fairly new to AJAX so please pardon my naivety.