Form validation with AJAX - preventing from blank fields - javascript

I have some script in JS which should validate my form. It shows information like 'sent' or 'loading' when processing. I'd like to add one more feature. I want to prevent users from sending an e-mail with blank fields. What should I add to the code below to achieve this?
$(function() {
var form = $('#form');
var submit = $('#submit');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '',
type: 'POST',
dataType: 'html',
data: form.serialize(),
beforeSend: function() {
document.getElementById("submit").value = "Loading...";
},
success: function() {
form.trigger('reset');
document.getElementById("submit").value = "Message sent!";
},
});
});
});

You could use HTML attribute required on the fields that cannot be empty
<input type="text" required/>
AND/OR
Have some javascript check before you submit
$(function() {
var form = $('#form');
var submit = $('#submit');
form.on('submit', function(e) {
e.preventDefault();
if($('input', this).val().trim() == ''){
//handle error message
}
else{
$.ajax({
url: '',
type: 'POST',
dataType: 'html',
data: form.serialize(),
beforeSend: function() {
document.getElementById("submit").value = "Loading...";
},
success: function() {
form.trigger('reset');
document.getElementById("submit").value = "Message sent!";
},
});
}
});
});
AND/OR
You do server side checking to make sure the value is not empty
in PHP:
if(empty($_POST['input_name'])){
//handle error
}

Related

Form submit on button click in a multistep form

I have a form which has a save and continue button. So I want the third click to submit the data. I have written the following code for it. But the submit portion doesn't work.
$(document).ready(function(){
var datastring="";
var d1= $( "#Submit3" ).mousedown(function() {
alert("Event occurred");
datastring = $("#reg_form").serialize();
console.log(datastring);
});
function submit()
{
$('form').submit(function(){
$.ajax({
type: "POST",
url: "reg.php",
data: datastring,
success: function(data) {
console.log('Data sent');
}
});
});
}
$.when(d1).done(submit());
});
Try the following code
$(document).ready(function(){
$( "#Submit3" ).on("click", function() {
alert("Event occurred");
dataString = $("#reg_form").serialize();
console.log(dataString);
submit(dataString);
});
function submit(dataString)
{
$.ajax({
type: "POST",
url: "reg.php",
data: dataString,
success: function(data) {
console.log('Data send');
}
});
}
});
You need to make the button type of the third button to "submit" and the type of other two buttons should be "button" just like this.
<button type="button">Save</button>
<button type="button">Continue</button>
<button type="submit">Submit</button>
So that when you click on the other two buttons form will not be submitted. Only on the click of third button, your form will be submitted. Here is the script to submit the form
$("form").submit(function(e){
e.preventDefault();
var formData=$("form").serialize();
console.log(formData);
$.ajax({
type: "POST",
url: "register.php",
data: formData,
success: function(response) {
console.log('Data send');
}
});
});

Prevent double submits form

I have a form which has a submit button. If I click this submit button then JSON will be posted to a webservice through AJAX:
$("#msform").submit(function (e) {
$.ajax({
url: 'https://example.com/webservice',
type: 'POST',
data: formData1,
crossDomain: true,
dataType: 'json',
jsonpCallback: 'callback',
success: function (data) {
console.log(data);
}
});
});
The webpage will also load and go to another page.. While loading the user can click multiple times on the Submit button, if he does that then for multiple times the AJAX post will be done to the webservice.
I tried this code to fix this but it does not work:
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function () {
$(this).on('submit', function (e) {
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
// Keep chainability
return this;
};
$('#msform').preventDoubleSubmission();
Any idea why double posting is not prevented??
The solution is to use a variable called wasSubmitted which verify if ajax request was already sent.
var wasSubmitted = false;
$("#msform").submit(function (e) {
if(!wasSubmitted) {
wasSubmitted = true;
$.ajax({
url: 'https://example.com/webservice',
type: 'POST',
data: formData1,
crossDomain: true,
dataType: 'json',
jsonpCallback: 'callback',
success: function (data) {
console.log(data);
}
});
return wasSubmitted;
}
return false;
});
I think a simple preventDefault would be enough
$("#msform").submit(function (e) {
e.preventDefault();
$.ajax(..)
The solution, that comes to my mind first, is to disable the button onclick with JS.
document.getElementById("btn_id").setAttribute("disabled","disabled");

JQuery required fields not stopping Ajax form submit

I'm using this code to submit a form using Ajax:
$(document).ready(function(){
$("#SubmitTicket").submit(function(e){
CheckRequired();
e.preventDefault();
dataString=$("#SubmitTicket").serialize();
$.ajax({
type: "POST",
url: "?SubmitTicket=1",
cache: false,
data: dataString,
success: function(res) {
if(res.indexOf("success")!=-1) {
//window.location.href = res.substr(8);
$("#CreateNewTicket_Body").html(res);
$("#CreateTicket").hide();
}
}
});
});
});
This function checks for required classes in form elements
function CheckRequired(event) {
var $form = $(this);
var emptyElements = $form.find('.required').filter(function() {
return this.value === ''
});
if(emptyElements.length > 0) {
event.preventDefault();
emptyElements.addClass("EmptySelect").attr('title', 'This field is required');
//alert(emptyElements.attr("id"));
alert("One or more fields cannot be blank");
return false;
}
}
I then have this code which automatically checks all my forms for required fields using the above function:
$(document).ready(function () {
$('form').on('submit', CheckRequired);
});
It works fine on forms that POST to another page.
When using the Ajax submit code, its display the alert when there is an error, but its still submitting the form.
You might want to enclose the return of CheckRequired into an if() structure :
$(document).ready(function(){
$("#SubmitTicket").submit(function(e){
if(CheckRequired.call(this,e)) { // this should refer to the event target element, i.e. the form element, providing context for the function
e.preventDefault();
dataString=$("#SubmitTicket").serialize();
$.ajax({
type: "POST",
url: "?SubmitTicket=1",
cache: false,
data: dataString,
success: function(res) {
if(res.indexOf("success")!=-1) {
//window.location.href = res.substr(8);
$("#CreateNewTicket_Body").html(res);
$("#CreateTicket").hide();
}
}
}
});
});
});
You can simply add onSubmit="return CheckRequired()" in your form.
If the 'CheckRequired()' return false, you need to stop the script by returning false.
$(document).ready(function(){
$("#SubmitTicket").submit(function(e){
e.preventDefault();
if (!CheckRequired(e)) {
return false;
}
dataString=$("#SubmitTicket").serialize();
$.ajax({
type: "POST",
url: "?SubmitTicket=1",
cache: false,
data: dataString,
success: function(res) {
if(res.indexOf("success")!=-1) {
//window.location.href = res.substr(8);
$("#CreateNewTicket_Body").html(res);
$("#CreateTicket").hide();
}
}
});
});
});
Two ways to approach this:
A) Javascript
$(document).ready(function(){
$("#SubmitTicket").submit(function(e){
if(!CheckRequired()) return false; // THIS!
e.preventDefault();
dataString=$("#SubmitTicket").serialize();
$.ajax({
type: "POST",
url: "?SubmitTicket=1",
cache: false,
data: dataString,
success: function(res) {
if(res.indexOf("success")!=-1) {
//window.location.href = res.substr(8);
$("#CreateNewTicket_Body").html(res);
$("#CreateTicket").hide();
}
}
});
});
});
B) HTML:
<form id="SubmitTicket" onSubmit="return CheckRequired();">

Preventing multiple form submittions with validation

Could someone please help me in locating where i need to place this code below into my validation script.
The script works great, but users are clicking more than once and the form is sending multiple times.
I tried including the code just below the if(valid) line but still does not work.
This is the code i am trying to include:
form.submit.disabled = true;
form.submit.value = "Please wait...";
This is the script:
<script type="text/javascript">
$(document).ready(function (e){
$("#nominateForm").on('submit',(function(e){
e.preventDefault();
var valid;
valid = validateContact();
if(valid) {
$.ajax({
url: "contact_mail.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#mail-status").html(data);
},
error: function(){}
});
}
}));
function validateContact() {
var valid = true;
$(".nominateForm").css('background-color','');
$(".info").html('');
if(!$("#nominate-name").val()) {
$("#nominateName-error").html("Please enter a name of who you would like to nominate");
valid = false;
}
return valid;
}
});
</script>
You should put those two lins inside the if condition and after the success call, you should turn them back into the default values. Also the correct way of accessing the properties of your submit button is like below,
$('input[type="submit"]').prop('disabled', true);
$('input[type="submit"]').prop('value', 'Please wait...');
or if it has an id equal to mySubmitBtn
$('#mySubmitBtn').prop('disabled', true);
$('#mySubmitBtn').prop('value', 'Please wait...');
So your code should be,
if(valid) {
$('input[type="submit"]').prop('disabled', true);
$('input[type="submit"]').prop('value', 'Please wait...');
$.ajax({
url: "contact_mail.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#mail-status").html(data);
$('input[type="submit"]').prop('disabled', false);
$('input[type="submit"]').prop('value', 'Submit');
},
error: function(){}
});
}
You can add an HTML element showing something like 'processing' and if it is processing, then skip the function.
<script type="text/javascript">
$(document).ready(function (e){
$("#nominateForm").on('submit',(function(e){
var status = document.getElementById('someHTMLElement');
if (status.innerHTML != 'processing') {
status.innerHTML = 'processing';
e.preventDefault();
var valid;
valid = validateContact();
if(valid) {
$.ajax({
url: "contact_mail.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#mail-status").html(data);
},
error: function(){}
});
}
status.innerHTML = '';
}
}));
function validateContact() {
var valid = true;
$(".nominateForm").css('background-color','');
$(".info").html('');
if(!$("#nominate-name").val()) {
$("#nominateName-error").html("Please enter a name of who you would like to nominate");
valid = false;
}
return valid;
}
});
</script>

Staying on page depending on value jquery

I want to stay on the same page if the login (data.login != 1) is incorrect , I tried with preventDefault but that's not working. Can anyone help me ?
$(document).on('submit', '#login', function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: $(form).serialize(),
dataType: 'json',
success: function(data) {
if (data.login === 1) {
$.mobile.changePage("<?php echo site_url('redirect/overview'); ?>");
} else {
e.preventDefault();
}
}
});
});
The page will submit before the result of ajax call is being received in success as you have asyn call, You can e.preventDefault() before ajax call and call submit on success.
$(document).on('submit', '#login', function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: $(form).serialize(),
dataType: 'json',
success: function(data) {
if (data.login === 1) {
$.mobile.changePage("<?php echo site_url('redirect/overview'); ?>");
}
else {
$('#submitButtonId')[0].submit();
}
}
});
});

Categories