How to Prevent Page from Reloading After Form Submit - Jquery

Stop form refreshing page on submit

You can prevent the form from submitting with

$("#prospects_form").submit(function(e) {
e.preventDefault();
});

Of course, in the function, you can check for empty fields, and if anything doesn't look right, e.preventDefault() will stop the submit.

Without jQuery:

var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {

e.preventDefault();

var name = $("#name").val();
var email = $("#email").val();

$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {

e.preventDefault();

var name = $("#name").val();
var email = $("#email").val();

$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="janedoe@email.com">

And then in your JS:

$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {

// Prevent form submission which refreshes page
e.preventDefault();

// Serialize data
var formData = $(this).serialize();

// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});

How to prevent page from refreshing after ajax submit

Calling $("#form").submit(function() { ... }) creates a handler for the next time the form is submitted. Doing this inside the handler for $("#submit").click() is not correct. Clicking the submit button will establish a handler for the next submission, but then the default action will submit the form immediately, which refreshes the page. Putting e.preventDefault() inside the click handlers would prevent the reload, but then you would have to click twice to submit the form (and this wouldn't actually work, because the default action of a submit button is to trigger the submit event, and you're preventing that).

Just create submit handlers for each form, without doing it inside a click handler.

$(document).ready(function() {
loadNewCourse();
loadDelTable();
$('#form').submit(function(e) {
e.preventDefault();
var in_arr = [],
name = ("<?php echo $_SESSION['name']?>"),
email = ("<?php echo $_SESSION['email']?>"),
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>"),
dept = ("<?php echo $_SESSION['dept']?>"),
semester = ("<?php echo $_SESSION['semester']?>");
$('.inChk').each(function(i) {
var checked = $(this).is(':checked');
if (checked) {
in_arr.push($(this).val());
}
});
$.ajax({
url: 'submit.php',
type: 'POST',
cache: false,
async: false,
data: {
post_inId: in_arr,
name: name,
email: email,
regno: regno,
level: level,
dept: dept,
semester: semester
},
success: function(data) {
loadNewCourse();
loadDelTable();
// setTimeout(function(){
// $('#regModal').modal('hide');
// }, 1000);
$('body').removeAttr('style');
$('#regModal').removeAttr('style');
$('.modal-backdrop').remove();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Registration successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data) {
swal("Oops...", "Registration failed.", "error");
}
});
});

////////////////////////////////////////////////////////////////////////////////////////
// PROCESS AJAX DELETE ON CHECKBOX SELECT
$('#delform').submit(function(e) {
e.preventDefault();
var id_arr = [],
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>");
$('.delChk').each(function(i) {
var checked = $(this).is(':checked');
if (checked) {
id_arr.push($(this).val());
}
});
swal({
title: "Are you sure you want to delete selected courses?",
text: "You can add these courses by registering again!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete!",
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
closeOnConfirm: false
},
function(isConfirm) {
if (isConfirm) {
$.ajax({
type: "POST",
url: "submit.php",
data: {
post_id: id_arr,
regno: regno,
level: level
},
cache: false,
async: false,
success: function(data) {
// console.log(data);
loadDelTable();
loadNewCourse();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Delete successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data) {
swal("Oops...", "Delete failed.", "error");
}
});
} else {
// alert('isNotConfirm and is not success');
swal("Oops...", "Delete failed", "error");
}
});
return false;
///////////////////////////////////////////////////////////////////////////////////////////
});

function loadNewCourse() {
$.ajax({
url: 'processReg.php',
type: 'POST',
cache: false,
async: false,
data: {
loadit: 1
},
success: function(disp) {
$("#reveal").html(disp).show();
}
});
}

function loadDelTable() {
$.ajax({
url: 'delete_tbl.php',
type: 'POST',
cache: false,
async: false,
data: {
loadDel: 1
},
success: function(deldisp) {
$("#showRegtbl").html(deldisp).show();
}
});
}
});

If you had multiple submit buttons in the same form you would instead assign click handlers to each button, but not create submit handlers for the form.

Submit form without page reload using jQuery - not working

I have managed to solve the problem myself. Being a complete beginner in JS, I am a bit disappointed nobody pointed out such an easy solution. I just needed to move the submission function inside the validation function. Now everything is working perfectly.

// Form Validation & Submission

$(document).ready(function () {

$("form").validate({

errorPlacement: function (error, element) {
$(element)
.closest("form")
.find("label[for='" + element.attr("id") + "'] > span")
.append(error);
},

errorElement: "span",

rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
subject: "required",
msg: "required",
checkbox: "required",
},

messages: {
firstname: "*required",
lastname: "*required",
email: {
required: "*required",
email: "*invalid email address"
},
subject: "*required",
msg: "*required",
checkbox: "*required",
},

submitHandler: function () {

var that = $('form'),
url = that.attr('action'),
type = that.attr('method'),
data = {};

that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();

data[name] = value;
});

$.ajax({

url: url,
type: type,
data: data,
success: function (response) {

console.log(response);

function resetForm () {
$('form')[0].reset();
};

resetForm();

$('.send').addClass('send-up');
$('.sent').addClass('sent-up');

setTimeout(function () {
$('.send').removeClass('send-up');
$('.sent').removeClass('sent-up');
}, 3000);

}
});

return false;

}
});

});
.form {
text-align: right;
font-family: sans-serif;
background: #000;
color: #FFF;
padding: 50px;
}

form {
text-align: left;
}

form li {
position: relative;
margin-bottom: 55px;
list-style-type: none;
}

.li-firstname,
.li-lastname {
width: 44%;
display: inline-block;
}

.li-firstname {
margin-right: 68px;
}

input,
textarea {
background: transparent;
border: 0;
outline: 0;
border-bottom: 2px solid #FFF;
display: block;
color: #FFF;
width: 100%;
padding: 15px 0 15px 30px;
box-sizing: border-box;
transition: border-bottom 0.3s ease-in-out;
resize: none;
}

.label {
position: absolute;
right: 0;
margin-top: 10px;
}

form i {
position: absolute;
bottom: 16.5px;
transition: color 0.3s ease-in-out;
}

.submit {
outline: 0;
border: 0;
color: #FFF;
padding: 0;
width: 243px;
height: 60px;
cursor: pointer;
position: relative;
background: #704DFA;
border-radius: 50px;
text-transform: uppercase;
}

.submit span {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transition: all 0.7s ease-out;
}

.send-up {
margin-top: -30px;
opacity: 0;
}

.sent {
margin-top: 30px;
opacity: 0;
}

.sent-up {
margin-top: 0;
opacity: 1;
}

input:focus,
textarea:focus {
border-bottom: 2px solid #704DFA;
}

input:focus+i,
textarea:focus+i {
color: #704DFA;
}

span.error {
font-family: sans-serif;
font-style: italic;
font-size: 13px;
color: #704DFA;
margin-right: 10px;
}

span.error:not(#checkbox-error) {
float: left;
margin-right: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://kit.fontawesome.com/a671c6b423.js" crossorigin="anonymous"></script>

<div class="form">
<form id="form" action="php/base.php" method="post">
<ul>
<li class="li-firstname">
<input type="text" name="firstname" id="firstname" required>
<i class="far fa-user"></i>
<label for="firstname" class="label"><span>First Name</span></label>
</li>
<li class="li-lastname">
<input type="text" name="lastname" id="lastname" required>
<label for="lastname" class="label"><span>Last Name</span></label>
</li>
<li class="li-email">
<input type="email" name="email" id="email" required>
<i class="far fa-envelope"></i>
<label for="email" class="label"><span>Email Address</span></label>
</li>
<li class="li-subject">
<input type="text" name="subject" id="subject" required>
<i class="far fa-question-circle"></i>
<label for="subject" class="label"><span>Subject</span></label>
</li>
<li class="li-message">
<textarea name="msg" id="msg" wrap="hard" rows="5" maxlength="2000" required></textarea>
<i class="far fa-comment-dots"></i>
<label for="msg" class="label"><span>Job Proposal</span></label>
</li>
<li class="li-checkbox">
<input type="checkbox" name="checkbox" id="checkbox" required>
<label for="checkbox">
You want to work with me specifically because you feel my style fits perfectly to your business.
</label>
</li>
</ul>
</form>

<button class="button submit" type="submit" form="form">
<span class="send">Submit</span>
<span class="sent">Sent</span>
</button>
</div>

How to prevent form to reload page after onsubmit

Prevent the default behavior of the submit using event.preventDefault. Then use ajax to submit the form value.

Also in addEventListener while attaching the event you dont need to immediately call the getGridValues, so avoid the () after the function name

function getGridValues(e) {  e.preventDefault();  const inputHeight = document.getElementById('inputHeight').value;  const inputWidth = document.getElementById('inputWidth').value;  console.log(`Height: ${inputHeight}, Width: ${inputWidth}`);
// Here use ajax to submit the value}
document.getElementById('submit').addEventListener("click", getGridValues);
<form id="sizePicker">  Grid Height:  <input type="number" id="inputHeight" name="height" min="1" value="1"> Grid Width:  <input type="number" id="inputWidth" name="width" min="1" value="1">  <input type="submit" id="submit"></form>

Stop page refresh after form submit

Preventing the default on the submit button should theoretically stop form submission—but:

  1. there is no submit event for an input button. If you listen to click, that will work, but only partially because...
  2. there might be other confounding factors that is interfering with this, i.e. other keystrokes or user interactions that causes the form to be submitted.

You should be listening to the onsubmit event fired from the form, instead of the event emitted from the submit button. The form's submit event is the definite event that is fired when a form is submitted: be it triggered by <button>, <input type="submit">, or even programatically, such as $form.trigger('submit'). You can give your form an ID, i.e.:

<form method="post" name="registerForm" class="form" id="registrationForm">

And then simply perform the exact same logic in the onsubmit callback:

$('#registrationForm').on('submit', function(e) {
// Prevent form submission by the browser
e.preventDefault();

// Rest of the logic
});

If you can't modify the DOM such that you can identify the <form> element, using jQuery's DOM traversal methods will also work, i.e.:

var $form = submitButton.closest('form');
$form.on('submit', function(e) {
// Prevent form submission by the browser
e.preventDefault();

// Rest of the logic
});

To illustrate my statement that the form's submit event serves as an "umbrella" that captures all submission events, regardless of how they are triggered, refer to the example I have attached below:

$(function() {  $('#form').on('submit', function(e) {    console.log('Form submission captured. It is triggered by: ', document.activeElement);    //e.preventDefault();  });    $('#submitInput').on('submit', function(e) {    console.log('Triggering submit event from <input>');  });    $('#submitButton').on('click', function() {    console.log('Triggering submit event from <button type="submit" />');  });
$('#submitProgramatically').on('click', function() { console.log('Triggering submit event using JS only'); $('#form').trigger('submit'); });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form id="form" action="#">  <input type="text" placeholder="Just another text field" />  <br />  <input type="submit" value="Submit using an <input>" id="submitInput" />  <br />  <button id="submitButton">Submit using a <button></button>  <br />  <a href="#" id="submitProgramatically">Submit programatically using JS</a></form>

Prevent page reload and redirect on form submit ajax/jquery

Modify the function like this:

function sendForm(e){
e.preventDefault();
}

And as comment mentions, pass the event:

onclick = sendForm(event);

Update 2:

$('#form-button-submit').on('click', function(e){
e.preventDefault();

var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;

$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});


Related Topics



Leave a reply



Submit