I am using an alert plugin and I want it to load the alert-success when the form is submitted under the .done function in my script. Plugin page here.
The plugin works with a button like this:
<button id="alert-success" class="bordered" >Try out!</button>
then when the user clicks the button it calls the jquery $(document).ready and executes the plugin. All I want to accomplish is to be loaded without the button when the form is submitted.
My form script:
var form = $('#contact');
form.submit(function (event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
var $form = $(this);
var name= $('#fname').val();
var email= $('#email').val();
var Message = $('#msg').val();
var selectedOption = document.getElementById("country").value;
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Email: email,
message: Message,
Country : selectedOption,
},
beforeSend: function () {
form.append(form_status.html(sending. . .
<i class="material-icons w3-spin w3-text-indigo" style="font-size:30px">mail_outline</i>').fadeIn()); }
}).done(function (data) {
form_status.html('<i id="alert-success" class="bordered material-icons w3-text-green" style="font-size:30px">done</i> message sent!').hide(10000);
});
document.getElementById("fname").value = "";
document.getElementById("email").value = "";
document.getElementById("country").value = "";
document.getElementById("msg").value = "";
});//end contact form
Script that executes when the button is clicked:
$(document).ready(function() {
var variants = {
'alert-success': {
args: [
{
content: 'Success! Message sent!',
icon: $.sweetModal.ICON_SUCCESS
}
]
},
};
for (var key in variants) {
if (variants.hasOwnProperty(key)) {
var variant = variants[key];
$('#' + key).on('click', { variant: variant }, function(e) {
var variant = e.data.variant;
variant.fn = variant.fn || $.sweetModal;
variant.fn.apply(this, variant.args);
});
} }
});
try adding this inside done method
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Email: email,
message: Message,
Country : selectedOption,
},
success:function()
{
// after success show modal
$.sweetModal({
title: "Title here",
message: "",
content: "Alert Success",
classes: ["success"],
showCloseButton: !0,
blocking: !0,
timeout: null,
theme: $.sweetModal.THEME_LIGHT,
type: $.sweetModal.TYPE_MODAL,
});
}
});
Customize as per your need. Customization options are on the plugin page
Related
We are using https://jqueryvalidation.org/ library to validate the contact form on our website.
The details will be sent to a 3rd party web service
jQuery("#contactform").validate({ // initialize the plugin
rules: {
name: {required:true},
email: {required:true},
phonenumber: {required:true}
},
submitHandler: function(form, evt) {
evt.preventDefault();
var name = jQuery('#name').val();
var email = jQuery('#email').val();
var phonenumber = jQuery('#phonenumber').val();
var contactform_url = jQuery("#contactform").attr('action');
jQuery.ajax({
type: "POST",
url: contactform_url,
cache: false,
data: {
name: name,
email: email,
phonenumber: phonenumber
},
beforeSend: function() {
}
}).done(function(data, textStatus, jqXHR) {
}).fail(function(jqXHR, textStatus, errorThrown) {
});
}
});
Problem: The current validation cannot prevent a user to input a url to the name input field
so var name = jQuery('#name').val(); can have a value of https://www.google.com/
Do you know how can I avoid users to input a link or url to our name input field or at least convert the url into a string?
Any help is greatly appreciated. Thanks
Try with following code hope it will work for you
$('#name').on('input', function() {
var input=$(this);
if (input.val().substring(0,4)=='www.'){input.val('http://www.'+input.val().substring(4));}
var re = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/;
var is_name=re.test(input.val());
if(is_name){
alert('valid');
}
}
else{
alert('invalid');
}
});
Your second condition ful fill here
var url = "google.com";
var lastCom = url.slice(-3);
alert(lastCom); // "com"
i have multiple identical forms (one for each month) that sit on multiple sections using this script :
http://www.jquery-steps.com/Examples
no problems there.
When i hit the next or previous buttons, i post the data on the form with this :
var tsf = $('.tsf-wizard-1').tsfWizard({
stepEffect: 'basic',
stepStyle: 'style1',
validation: false,
navPosition: 'top',
manySteps: true,
stepTransition: true,
showButtons: true,
showStepNum: true,
height: '500px',
prevBtn: '<i class="fa fa-chevron-left"></i> Vorige Maand',
nextBtn: 'Volgende Maand <i class="fa fa-chevron-right"></i>',
finishBtn: '<i class="fa fa-table"></i> Overzicht',
onNextClick: function (e, from, to, validation) {
var stap = from+1;
var formstep = '#'+stap.toString()+'_form';
var pathname = window.location.pathname; // Returns path only
var url = window.location.href;
$.ajax({
type: 'post',
url: 'user_settings/add_data',
data: $(formstep).serialize(),
success: function () {
console.log($(formstep).serialize());
},
error: function (){
$( "#remarks").html("<span class=\"label label-danger\">ERROR !</span> Problem saving..");
}
});
},
onPrevClick: function (e, from, to, validation) {
var stap = from+1;
var formstep = '#'+stap.toString()+'_form';
$.ajax({
type: 'post',
url: 'user_settings/add_data',
data: $(formstep).serialize(),
success: function () {
console.log($(formstep).serialize());
},
error: function (){
$( "#remarks").html("<span class=\"label label-danger\">ERROR !</span> Problem saving..");
}
});
}
});
But, when the user leaves the page i want to have all of the forms posted with an ajax call. So i tried this (The hold.open and .close is busy indicator)
$(window).on('beforeunload', function ()
{
//this will work only for Chrome
pageSave();
});
$(window).on("unload", function ()
{
//this will work for other browsers
pageSave();
});
function pageSave()
{
if (!_wasPageSaved)
{
HoldOn.open({
theme:'sk-cube-grid',
message:"<h4>Savig data..</h4>"
});
var goodsaves=0;
for (i = 1; i <= 12; i++) {
var formstep = '#'+i.toString()+'_form';
$.ajax({
type: 'post',
url: '<?php echo base_url();?>user_settings/add_data',
data: $(formstep).serialize(),
success: function () {
goodsaves=goodsaves+1;
},
error: function (){
console.log('error saving data :');
}
});
}
HoldOn.close();
if (goodsaves=>11) {
_wasPageSaved = true;
console.log('all forms saved');
}
}
}
Problem is that sometimes the data is saved, sometimes not. I can't put my finger on it why it doesn't always work . I see the busy indicator, i don't get any alerts in my console and the next page is loaded. But my data isn't saved...
hope anyone can clear this out , thanks allot in advance.
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;
}
});
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();
};
});
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')