Reputation: 425
In my HTML form I want to display a confirm()
box before the user goes to the next page. I am using jQuery AJAX with an onsubmit
attribute on the form
.
The problem is that the AJAX request runs every time, even if I click on the cancel button in the confirm dialog box. How can I stop the AJAX request when the user clicks cancel in the confirm box?
<form onsubmit="return confirm('Do You want to Continue?');" action="#" id="renewbyuser" method="POST">
<input class="renew button dark-gray" type="submit" name="renewnow" value="Renew Now">
</form>
$(document).ready(function() {
$("#renewbyuser").submit(function(e) {
$.ajax({
// ajax runs here
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
Upvotes: 1
Views: 1220
Reputation: 121
The easy way is not to use form to submit data to backend. You just need to use ajax to post data and prevent action like that:
HTML:
<form>
<button class="renew button dark-gray" id='btn-submit' name="renewnow" value="Renew Now">
</form>
jQuery:
$(document).ready(function() {
$("#btn-submit").on('click',(e) =>{
let check =confirm("do u want to continue!");
if(check){
$.ajax({
type : 'post',
url: 'formSubmitUrl'
data : dataForm
}).done((result)=>{});
}
});
});
or use jqueryForm
library to do you want
Upvotes: 1
Reputation: 337714
The issue is because you're assigning two individual event handlers, so although you prevent the first based on the result of confirm()
, the submit
event you listen to through jQuery still fires.
To fix this, put the confirm()
call within the submit
event handler and remove the onsubmit
attribute from the form
tag in your HTML:
<form action="#" id="renewbyuser" method="POST">
<input class="renew button dark-gray" type="submit" name="renewnow" value="Renew Now" />
</form>
$(document).ready(function() {
$("#renewbyuser").submit(function(e) {
e.preventDefault();
if (!confirm('Do You want to Continue?'))
return;
$.ajax({
// ajax runs here
});
});
});
Upvotes: 1