Javascript modal auto close after message - javascript

I am using below java script for contact form submission & after particular time the modal should be closed automatically
if ($('.js-form').length) {
$('.js-form').each(function() {
$(this).validate({
errorClass: 'error form-error',
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "mail.php",
data: $(form).serialize(),
success: function() {
$('#error').modal('hide');
$('#success').modal('show');
},
error: function() {
$('#success').modal('hide');
$('#error').modal('show');
}
});
}
});
});
}

You need to return false at the end of submission of your form.

You could use setTimeout() inside the handlers like this.
success: function() {
$('#error').modal('hide');
$('#success').modal('show');
setTimeout(function(){
$('#success').modal('hide');
}, 3000);
},
error: function() {
$('#success').modal('hide');
$('#error').modal('show');
setTimeout(function(){
$('#error').modal('hide');
}, 3000);
}

To close after a particular time, you have to use setTimeOut. with your current code, the hide/show functionality will execute immediately after the ajax response.

Related

AjaxSubmit submits form twice (or three times or 20 times)

I'm new here and new to JS :-)
I'm using AJAX SUBMIT (jquery) to send files to my CDN.
the first time - everything is ok, the file is sent and received.
second time: the file is sent and received, only it does that twice.
and the third time its three times etc...
that's the console of the second time: https://prnt.sc/tluygu
as you can see, it submits twice.
That's the code of the submission: (it's in a modal)
$(document).on('click', '.add-video-btn', function() {
$('#file').val('');
$('#file-upload').trigger('reset');
$('#video-uploading-modal').modal({
backdrop: 'static',
keyboard: false
});
$('#upload-btn').on('click', async function() {
var vidRes = await getOneTimeUploadUrl();
console.log(vidRes.result.uploadURL);
var oneTimeUrl = vidRes.result.uploadURL;
$('#file-upload').ajaxSubmit({
url: oneTimeUrl,
beforeSubmit: function(formData, formObject, formOptions) {
console.log(formData);
$('.progress').slideDown();
},
beforeSend: function() {},
uploadProgress: function(event, position, total, precentComplete) {
$('.progress-bar').css('width', precentComplete + '%');
$('.progress-bar').html('%' + precentComplete);
},
success: function(response) {
console.log(response);
alert('success');
},
});
});
});
The problem is that every time the modal is opened, a new submit listener gets added. To fix your problem, you need to split the event handlers:
Start with the modal click listener:
$(document).on('click', '.add-video-btn', function() {
$('#file').val('');
$('#file-upload').trigger('reset');
$('#video-uploading-modal').modal({
backdrop: 'static',
keyboard: false
});
});
Then, set the submit listener sepparately:
$('#upload-btn').on('click', async function() {
var vidRes = await getOneTimeUploadUrl();
console.log(vidRes.result.uploadURL);
var oneTimeUrl = vidRes.result.uploadURL;
$('#file-upload').ajaxSubmit({
url: oneTimeUrl,
beforeSubmit : function(formData, formObject, formOptions) {
console.log(formData);
$('.progress').slideDown();
},
beforeSend : function() {
},
uploadProgress : function(event, position, total, precentComplete) {
$('.progress-bar').css('width', precentComplete + '%');
$('.progress-bar').html('%' + precentComplete);
},
success: function(response) {
console.log(response);
alert('success');
},
});
});
That should solve your issue. Hope you've found this helpful.

.focusout() fires twice on second event jQuery

When I am using the .focusout() function in jQuery it seems to fire twice when I trigger the event for the second time, here is an example of my code:
$(document).ready(function() {
var baseUrl = "http://annuityadvicecentre.dev/";
if($('html').hasClass('ver--prize-soft')) {
$('#home_telephone').focusout(function () {
var softResponse = {};
var inputVal = $(this).val();
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type: 'POST',
url: baseUrl + "lookup",
data: {
number: inputVal,
phone_type: "mobile",
},
error: function() {
console.log('POST Error: Mobile');
},
}).done(function(data) {
// you may safely use results here
softResponse.isMobile = data;
});
$.ajax({
type: 'POST',
url: baseUrl + "lookup",
data: {
number: inputVal,
phone_type: "landline",
},
error: function() {
console.log('POST Error: Landline');
},
}).done(function(data) {
// you may safely use results here
softResponse.isLandline = data;
});
$(document).ajaxStop(function () {
console.log('All AJAX Requests Have Stopped');
});
});
}
});
Sorry for the messy example as I have just been bootstrapping this up however you can see I am wrapping this focusout function:
$('#home_telephone').focusout(function () {...
Around my AJAX calls, now for some reason when I test this out on the page and un-focus on the #home_telephone element the .ajaxStop() function only runs once which is the functionality I want however if I then click on the element and un-focus again the .ajaxStop() function runs twice. Any idea why this might be happening? Thanks
Try to add e.stoppropogation() within function like:
$('#home_telephone').focusout(function (e) {
e.stopPropagation()();
//your code
});
You're adding a new ajaxStop listener every time the element is unfocused. Just move the:
$(document).ajaxStop(function () {
console.log('All AJAX Requests Have Stopped');
});
call outside of the focusout callback function.

jQuery PHP Ajax Check User Logged in show modal

I have jQuery PHP Ajax to check user logged in or not.
JS
jQuery(document).ready(function()
{
setInterval(function()
{
jQuery.ajax({
url: 'chkLoggedin.php',
type: 'POST',
success:function(response)
{
if(response == "sessionExpired")
{
bootbox.dialog(
{
message: "Please login to continue",
title: "Not logged in",
buttons:
{
success:
{
label: "Log in",
className: "btn-success",
callback: function()
{
$('.bootbox').modal('hide');
}
}
}
});
return false;
}
}
});
}, 5000);
});
PHP
require("config/db.php");
session_start();
include("config/session.php");
if(empty($session))
{
echo "sessionExpired";
}
I tried the above code is working, but after logout the modal show multipe until I refresh the page. I just want the modal show 1 time.
Use setTimeOut function instead of setInterval

jquery date picker is not work when i put datepicker on ready after ajax call

I want to know that my jquery-ui datepicker is not working in document.ready after an ajax function call. when I put on ajax complete its work successfully please help what should I do. what's the reason for not working
$("#ScheduledArrivalDate").datepicker({
beforeShow: function () {
setTimeout(function () {
$('.ui-datepicker').css('z-index', 2000);
}, 0);
}
});
function getPage(page) {
$.ajax({
type: "POST",
url: page,
data: $("#frm").serialize(),
xhrFields: {
withCredentials: true
},
success: function (html) {
$('#List').empty();
$('#List').append($.parseHTML(html));
},
error: function () {
alert("error");
},
complete: function () {
alert("complete");
}
});
}
$.document.ready() only initiates after a page is loaded without ajax. When you replace/append html in an ajax call and you have a datefield in the new inserted html, you need to initialise it again (at least for the new inserted html block).
You could do this by calling $.datepicker in your success or complete function, like you already did, or by adding $.document.ajaxEnd() to your javascript file, what is initialized after every end of an ajax event (also on error).
Be aware not do double initiate the datepicker, especially when using ajaxEnd. This could lead to unexpected behaviour.
the code inside $(document).ready() will run only after page loads. While you are dynamically adding datepicker if I am not wrong. So do one thig. Take options in a variable like below:
var options = {
beforeShow: function () {
setTimeout(function () {
$('.ui-datepicker').css('z-index', 2000);
}, 0);
}
}
then:
$(document).ready(function(){
$("#ScheduledArrivalDate").datepicker(options);
});
and in ajax call:
function getPage(page) {
$.ajax({
type: "POST",
url: page,
data: $("#frm").serialize(),
xhrFields: {
withCredentials: true
},
success: function (html) {
$('#List').empty();
$('#List').append($.parseHTML(html));
$('#IdOfnewlyAddedDatePicker').datepicker(options);
},
error: function () {
alert("error");
},
complete: function () {
alert("complete");
}
});
}
Let me know if this not work or you are injecting html other than this.

jQuery click handler not executing AJAX POST

Note: I personally prefer jQuery instead of $; it's more typing but I find it more readable.
I have a simple form that lets the user enter their first/last names and email address. It has a "Save" button, that, when clicked, executes:
jQuery('#saveButton').click(function() {
alert('About to Save to server');
var validated = validateContact();
if(!validated) {
alert('Did not validate!');
return;
} else {
alert('Validated!');
}
jQuery().ajax({
url: "saveContact",
type:"post",
dataType: 'json',
data: {
contact: {
firstName: jQuery('#firstName').val(),
lastName: jQuery('#lastName').val(),
emailAddress: jQuery('#emailAddress').val()
}
},
success: function(result) {
jQuery('#firstName').val("");
jQuery('#lastName').val("");
jQuery('#emailAddress').val("");
},
error: function(xhr){
alert(xhr.responseText);
}
});
alert('Saved to server');
});
When I click the "Save" button, I get several alert popups, including the "Validated!" message, however the script seems to die shortly after that, and I never see the "Saved to server" alert. This tells me my jQuery/AJAX call is bad. Furthermore, when I open my browser's Developer Tools, I don't see the browser actually making a network POST to my backend. In the console I don't see any errors. Any ideas as to where I'm going wrong and why I'm not even seeing any network activity?
Replace jQuery().ajax with jQuery.ajax({...})
Following Errors in your code:
Used jquery instead of jQuery.
Used jQuery() instead of jQuery in calling ajax method.
JS:
jQuery('#saveButton').click(function () {
alert('About to Save to server');
var validated = true; //Changed to temporary value.
if (!validated) {
alert('Did not validate!');
return;
} else {
alert('Validated!');
}
jQuery.ajax({ //Replaced jQuery() with jQuery
url: "/saveContact", //Sample URL
type: "post",
dataType: 'json',
data: {
contact: {
firstName: jQuery('#firstName').val(), //Replaced jquery with jQuery
lastName: jQuery('#lastName').val(), //Replaced jquery with jQuery
emailAddress: jQuery('#emailAddress').val() //Replaced jquery with jQuery
}
},
success: function (result) {
jQuery('#firstName').val(""); //Replaced jquery with jQuery
jQuery('#lastName').val(""); //Replaced jquery with jQuery
jQuery('#emailAddress').val(""); //Replaced jquery with jQuery
},
error: function (xhr) {
alert(xhr.responseText);
}
});
alert('Saved to server');
});
Demo: http://jsfiddle.net/lotusgodkk/x2mv94vm/6/

Categories

Resources