This script uses the $ .ajax.abort () method to cancel the request if it is active. It uses the readyState property to check if the request is active or not.
This is a working script
HTML
<h3>Cancel Ajax Request on Demand</h3> <div id="test"></div> <input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />
JS code
//Initial Message var ajaxRequestVariable; $("#test").html("Please wait while request is being processed.."); //Event handler for Cancel Button $("#btnCancel").on("click", function(){ if (ajaxRequestVariable !== undefined) if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4) { ajaxRequestVariable.abort(); $("#test").html("Ajax Request Cancelled."); } }); //Ajax Process Starts ajaxRequestVariable = $.ajax({ method: "POST", url: '/echo/json/', contentType: "application/json", cache: false, dataType: "json", data: { json: JSON.encode({ data: [ {"prop1":"prop1Value"}, {"prop1":"prop2Value"} ] }), delay: 11 }, success: function (response) { $("#test").show(); $("#test").html("Request is completed"); }, error: function (error) { }, complete: function () { } });
vibs2006 Sep 14 '17 at 8:30 2017-09-14 08:30
source share