Sometimes you might want to cancel the ajax request that is pending from long time or want to cancel request if user accidently clicked submit button.
In that cases, so you can just use abort()
method. If the request has been sent already, this method will abort the request.
See the below example. First create form page which will create Ajax request. Now we will add setTimeout()
method which abort the Ajax request after one second. Save this file as index.html
file.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<input type="email" id="email" placeholder="Your E-Mail Address" />
<button type="submit" id="submit-form">Send</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-form').click(function(event) {
event.preventDefault();
var email = $('#email').val();
// create request
var xhr = $.ajax({
type: "POST",
url: "submit.php",
data: "email="+email,
success: function(resp) {
alert(resp);
}
});
// cancel request after 1 second
setTimeout(function() {
xhr.abort();
alert("Request canceled.");
}, 1000);
});
});
</script>
</body>
</html>
In the submit.php
file set 30 seconds pending time to return response.
<?php
$email = $_POST['email'];
sleep(30);
echo($email);
Note: I have created submit.php file only to wait so timeout() runs before Ajax request completed. You can set Ajax route anyone which takes time more than 1 second.
In case you are using Javascript Ajax object instead of JQuery, here is GET request example.
var xhr = new XMLHttpRequest(),
method = "GET",
url = "https://laravelcode.com/request";
xhr.open(method, url, true);
xhr.send();
if (true) {
xhr.abort();
}
I hope it will help you.