Last active
July 7, 2024 19:34
-
-
Save gr1zix/22adf52f9b714fa914ba2b35b7a4fa72 to your computer and use it in GitHub Desktop.
Stop all active Ajax requests in jQuery + Prevent Wordpress request abuse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.xhrPool = { | |
pool: [], | |
abortAll: function() { | |
$.each(this.pool, function(idx, jqXHR) { | |
jqXHR.abort(); | |
}); | |
this.pool = []; | |
}, | |
add: function(jqXHR) { | |
this.pool.push(jqXHR); | |
}, | |
remove: function(jqXHR) { | |
let index = this.pool.indexOf(jqXHR); | |
if (index > -1) { | |
this.pool.splice(index, 1); | |
} | |
} | |
}; | |
$.ajaxSetup({ | |
beforeSend: function(jqXHR) { | |
$.xhrPool.add(jqXHR); | |
}, | |
complete: function(jqXHR) { | |
$.xhrPool.remove(jqXHR); | |
} | |
}); | |
// Usage | |
searchInput.on('input', function() { | |
clearTimeout(debounceTimeout); | |
debounceTimeout = setTimeout(function() { | |
const query = searchInput.val().trim(); | |
$.xhrPool.abortAll(); | |
if (query.length > 2) { | |
search(query) | |
} else { | |
searchResults.empty(); | |
} | |
}, 300); | |
}); | |
function search(query) { | |
$.ajax({ | |
url: header_ajax_search_params.ajaxurl, | |
type: 'POST', | |
data: { | |
action: 'ajax_search', | |
_wpnonce: header_ajax_search_params._wpnonce, | |
keyword: query | |
}, | |
success: function(data) { | |
if (data.length > 0) { | |
const resultsHtml = data.map(function(item) { | |
return ` | |
<div class="search-result-item"> | |
<img src="${item.thumbnail}" alt="${item.title}"> | |
<span>${item.title}</span> | |
</div>`; | |
}).join(''); | |
searchResults.html(resultsHtml); | |
} else { | |
searchResults.hide(); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment