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

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();
};
});

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;
});
});

Ios devices, "required" field and thank you message

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;
}
});

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
});

Jquery close popup on click

I use this jquery to show my popup,
//ResetPassword Popup display
$(document).ready(function () {
var passwordExpiredVal = $("#isPasswordExpired").html();
if (passwordExpiredVal == "True") {
$("#ResetPasswordModal").modal({
show: 'true'
});
};
});
I use this jquery to pass the new typed password to controller action ON CLICK, once the save button is clicked I want the popup to close
//Reset Password submit
$(document).ready(function () {
$("#submitSave").on("click", function () {
var confirmPassword = $("#txtLgnPasswordConfirmReset").val();
var passwordReset = {
UserName: $("#txtLgnUsername").val(),
Password: $("#hdnOldPassword").val(),
NewPassword: $("#txtLgnPasswordReset").val()
}
if (passwordReset.NewPassword != confirmPassword) {
notifyMessage.showNotifyMessage('error', 'The passwords entered should match', false);
$("#txtLgnPasswordReset").val("");
$("#txtLgnPasswordConfirmReset").val("");
}
else {
$.ajax({
type: "POST",
url: "/Account/PasswordReset",
data: passwordReset,
success: function () {
$("#ResetPasswordModal").modal({
show: 'false'
});
},
error: function () {
alert('failure');
}
});
}
});
});
My jquery function is not helping...
success: function () {
$("#ResetPasswordModal").modal({
show: 'false'
});
},
Any ideas??
Thanks in advance...
The code you are using is unnecessarily initializing the modal again on that element.
Use modal('hide') : Docs,
success: function () {
$('#ResetPasswordModal').modal('hide');
},
If you further wish to use this again, 'toggle' would be a better option.
$('#ResetPasswordModal').modal('toggle')

Abort AJAX and form submitions, save them, change them, and send it later

I need to request additional credentials to a user when he clicks certain buttons and submits certain forms.
I way I am trying to do it is:
Intercept the submit event, abort it, and store a copy
Ask for the credentials with an prompt dialog (not the JS native one, so this is all non-blocking)
If user inputs the credentials, insert the fields into the event data and send it to the server.
My current code for AJAX requests is:
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
if (ajaxOptions.type === "POST") {
$.current_request = jqXHR;
jqXHR.abort();
$.check_password_with_my_dialog();
}
});
$.check_password_with_my_dialog: function() {
$("#validate-password-prompt").dialog({
modal: true,
title: "input pw",
buttons: {
Ok: function() {
$.password = $("#validate-password-prompt input").val();
$.deliver_current_request();
return $(this).dialog("close");
},
Cancel: function() {
return $(this).dialog("close");
}
}
});
}
deliver_current_request: function() {
$.current_request.beforeSend = function(jqXHR, ajaxOptions) {
ajaxOptions.data = ajaxOptions.data.concat("&password=" + $.password);
};
$.ajax($.current_request);
}
The problem so far is that ajaxOptions.data is undefined, so I can't add my data.
And the requests seems to be going as a GET instead of POST.
Am I doing this the right way, or am I way of?
updated
Here is a way i can think of to accomplish answer for your question.
<form id="myForm" >
<button id="submit-form-btn">Submit</button>
</form>
<div id="validate-admin-password-prompt">
<input type="password"/>
</div>
In javascript,
function submitForm(pwd) {
var formData = $('form#myForm').serialize() + "&password=" + pwd;
$.ajax({
type: "POST",
url: "http://google.com",
data: formData,
dataType: "script"
});
alert("POSTed: " + formData.toString());
}
function alertDialog() {
$("#validate-admin-password-prompt").dialog({
modal: true,
title: "Admin password is required",
zIndex: 10000,
buttons: {
Ok: function() {
$(this).dialog("close");
var pwd = $("#validate-admin-password-prompt input").val();
submitForm(pwd);
},
Cancel: function() {
$(this).dialog("close");
alert('Not authorized to submit the form');
return false;
}
}
});
}
$("#submit-form-btn").click(function(e) {
e.preventDefault();
$ele = $("#validate-admin-password-prompt input");
if ($ele.val()==null || $ele.val().trim()=="") {
alertDialog();
} else {
submitForm($ele.val());
}
});

Categories