Ios devices, "required" field and thank you message - javascript

I would like to merge two JavaScripts. The first one is using ajax to send message and the second one to alert user about required field in the contact form.
I want to merge this two, maybe with an IF statement, so first to check all fields and then to send message.
1 with ajax JavaScript:
$('document').ready(function () {
$('form#contact-form').submit(function () {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function () {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
return false;
});
});
2 alert JavaScript:
$('document').ready(function () {
$('form#contact-form').submit(function(e) {
var ref = $(this).find("[required]");
$(ref).each(function(){
if ( $(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
e.preventDefault();
return false;
}
}); return true;
});
});
From the answer below i have create the following code.
I made this link if someone wants to help. The alert works fine but the code not stop. It continue to load the rest code.
https://jsfiddle.net/L8huq1t1/

You can do this by the following code.
function checkValidation() {
var ref = $(this).find("[required]");
$(ref).each(function(){
if ( $(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
//e.preventDefault();
return false;
}
});
return true;
}
$('document').ready(function () {
$('form#contact-form').submit(function () {
if(!checkValidation()) {
return false;
}
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function () {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
return false;
});
});
But I give you a suggestion to use jquery.validate plugin which is better option. But if you still want to do like this, go ahead this is also works fine.

You can use jQuery Validation plugin that has a form submit handler where you can put your AJAX. Link to the plugin.
Your code should look something like this:
$('#contact-form').validate({
rules: {
your_input_name: {
required: true
}
},
messages: {
your_input_name: {
required: 'Field is required'
}
},
submitHandler: function() {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function() {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function() {
form.html(msg).fadeIn();
});
}
});
return false;
}
});

Related

jQuery Ajax submitting form multiple times

I am new to Ajax. I am currently submitting a form into my database using jQuery AJAX but it sends the same data multiple times in my database.
Here's my Ajax code :
$(document).ready(function () {
var id_js;
$(document).on('click', '.btn-success', function () {
id_js = $('#ID_TXT').val();
$('form').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
return false;
});
});
});
Also I have tried .one() and .stopImmediatePropogation() but still no results
I see both form submit and Ajax call are doing the same work. If you are going to post the data only with AJAX call then form submit is not required.
I hope this works well for you.
$(document).ready(function () {
function postDataToServer() {
var id_js = $('#ID_TXT').val();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
}
$(document).on('click', '.btn-success', postDataToServer);
});
The submit handler shouldn't be inside the click handler. Every time you click on the button, it adds another submit handler. So when you finally submit the form, it will submit it as many times as you clicked on the button.
If you want to ensure that the form isn't submitted until you've clicked on the button, add a test in the submit handler.
$(document).ready(function() {
var id_js;
$(document).on('click', '.btn-success', function() {
id_js = $('#ID_TXT').val();
});
$('form').submit(function(e) {
if (id_js !== undefined) {
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function(response) {
$('#result').html(response);
}
});
} else {
alert("You need to click on the success button first");
}
return false;
});
});

Ajax call function on success return false not working

I am running an ajax request, then once I get the result back I choose if it should be continued or if the form should not submit. I am checking if the email exists.
Issue is I moved the return false out of the success: as it was not working there and now in a seperate function it is not working either. I get the alert("FALSE"); but the form still submits which is no good as I want an error pop up to happen.
$.ajax({
type: "POST",
url: "/ajax/checkdata.php",
data: "email="+email,
success: function(data){
var returned = true;
if (data == "Email Exists") {
returned = false;
} else {
}
emailModal(returned);
}
})
function emailModal(result){
if (result) {
alert("TRUE");
} else {
alert("FALSE");
return false;
}
}
You'd have to always prevent the form from submitting, and then in the check for the email figure out wether to show an error or submit the form using the native submit handler
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/ajax/checkdata.php",
data: {email : email},
context: this
}).done(function(data) {
if (data == "Email Exists") {
alert(data);
} else {
this.submit();
}
});
});

preventDefault() and 2 functions

On my website users can add a text dynamically and remove it dynamically (via AJAX).
The problem is when users want to add a text and remove it immediately.
The suppression isn't realized (submit of deletion form is not detected).
$(document).ready(function() {
$(function(){
/* ADD A TEXT */
$("#formAdd").submit(function(evt) {
evt.preventDefault();
var text = $(this).find("textarea").val();
if (text) {
var url = $(this).attr('action');
form = $(this).serialize();
$.ajax({
type : "POST",
url : url,
dataType : "json",
data: {
"form" : form,
"form-type" : $(this).find(':submit').attr("name")
},
success: function(data){
document.getElementById("visualisation").html = text;
},
statusCode: {
400: function() {
alert("error");
}
}
});
}
});
/* REMOVE A TEXT */
$('#formDelete').submit(function(e) {
alert("CHECK !");
var idText = $(this).find('#text_visualisation').val();
form = $(this).serialize();
$.ajax({
type:"POST",
url: $(this).attr('action'),
dataType : "json",
data: {
'form' : form,
"form-type" : $(this).find(':submit').attr("name"),
},
success: function(data) {
$("#text").remove();
$("#modal_deleteForm").modal('hide');
},
statusCode: {
400: function() {
alert("error");
}
}
});
return false;
});
});
});
So the alert("CHECK !"); is not realized when I want to delete a text just after added this text. Why ?
I find the solution after a lot of hours of research... The probleme isn't preventDefault() but innerHTML (you couldn't now it, I'm sorry).
But I don't understand why use innerHTML can blocked jquery submission of form...
Thank's

form submit before ajax request completes

i am newbie to jquery.I called a ajax when submit the form.But form submits before ajax complete the request.How to fix this issue? Below is my code
$("#formSearch").submit(
function() {
if (checkUserNumber($("#UserNumber").val())) {
$.ajax({
type : 'post',
url : 'CheckDetails.do',
data : {
userNumber:$("#UserNumber").val()
},
success : function(data) {
if (data == 'EI') {
$("#ErrMsg").text(
'User Number does not exist');
return false;
} else {
return true;
}
}
});
} else {
return false;
}
});
Any help will be greatly appreciated!!!
use event.preventDefault(); to prevent the form submission.
$("#formSearch").submit(
function(event) {
event.preventDefault();
...
...
....
});
You can apply trick to achieve your requirement, add a data attribute to target form as follows
<form id="formSearch" data-prevent-default="1">
set default value to data-prevent-attribute=1 than you can rewrite your jquery submit function as follows:
$("#formSearch").submit(function (e) {
if ($(this).data("prevent-default") === 1) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'CheckDetails.do',
data: {
userNumber: $("#UserNumber").val()
},
success: function (data) {
//on success change the value of data attribute to 0
$("#formSearch").data("prevent-default", "0");
$("#formSearch").submit(); //than call form submit again
}
}).fail(function () {
});
}
//otherwise it will submitted by default
});

AJAX Form still submitting (in Safari) with Happy.js

HTML5 validation isn't working in Safari so I'm using Happy.js.
My form is still submitting via ajax in Safari though with the code below (here is JSFiddle).
How can I validate #email-input before sending the form with ajax?
The code below is checking if ($(this).hasClass('unhappy')) then don't submit form, if it doesn't have class unhappy then submit form. But I guess the problem is that it doesn't have class unhappy from the beginning.
used from this reference: isHappy.js allowing ajax call when not valid
$(document).ready(function() {
function ajaxEmailForm() {
$(".sendingEmailLink, .sentEmailLink").hide();
$('#email-form').submit(function(event) {
event.preventDefault();
var formserialize = $(this).serialize();
var submitButton = $('#submitEmailForm');
$.ajax({
type: 'POST',
url: 'https://formkeep.com/f/MYID',
accept: {
javascript: 'application/javascript'
},
data: formserialize,
beforeSend: function() {
$(".sendEmailLink").hide();
$('.sendingEmailLink').show();
},
complete: function() {
$(".sendingEmailLink").hide();
},
success: function(d) {
$('.sentEmailLink').show();
},
error: function() {
$('.notification-e--phone').slideDown("medium", function() {});
},
}).done(function(data) {
submitButton.prop('disabled', 'disabled');
});
});
};
$('#email-form').isHappy({
fields: {
'#email-input': {
required: true,
test: happy.email,
message: 'Please enter your full email address.',
errorTarget: '.email-input-error'
}
}
});
var is_unhappy = false;
$('#email-form div :input').each(function(i) {
if ($(this).hasClass('unhappy')) {
is_unhappy = true;
return false;
}
});
if (!is_unhappy) {
ajaxEmailForm();
};
});

Categories