Replace button before ajax call and then revert back after call - javascript

I have a button on my webpage that is generated like this :
<div class="btn2" id="btPost" onclick="$('#Delete').val('False'); ValidateFormAndAjaxSubmit('frmEditPost', this);" onmousedown="this.className='btn2_click';" onmouseout="this.className='btn2';" onmouseover="this.className='btn2_hover';" onmouseup="this.className='btn2_hover';">
<span>Posta</span>
</div>
When I have this javascript :
function ValidateFormAndAjaxSubmit(formId, callingElement) {
if (IsNotDblClick(callingElement.id)) {
var _form = $("#" + formId);
var validator = _form.validate();
var anyError = false;
anyError = !_form.valid();
if (anyError) {
window.latestClick = '';
return false; // exit if any error found
}
$.post(_form.attr("action"), _form.serialize(), function (data) {
if (data.success && data.redirectUrl.length > 0) {
window.location.href = data.redirectUrl;
}
else {
var isValid = validateResponse(_form, data);
window.latestClick = '';
}
})
}
}
This is working fine, but the problem is that I want to show the enduser that the form is loading. The best solution might be to simple remove the callingElement from the webpage and replace it with a temporary disabled(special CSS) button. The button needs to return then the ajax method is done.
I know about this :
$("#regTitle").html("Hello World");
But it is only replacing inner part of the div and I do also need to store the current markup to beable to go back when the ajax call is done.
It would also be good if the text within the span is placed also on the temporary button.
The question is how I do this as simple as possible?

Try this
$.ajax({
'type': 'POST',
'url': _form.attr("action"),
'data': _form.serialize(),
'beforeSend': function() {
$('.btn2').hide();
$('#regTitle').html('Loading ...');
$('#regTitle').show();
},
'success': function() {
$('.btn2').show();
$('#regTitle').hide();
},
'error': function() {
$('.btn2').show();
$('#regTitle').html('Error ...');
}
});

This is how I solved it :
Generate extra hidden div under the botton like this :
<div class="loadingDiv" id="loadingDiv_btPost"></div>
with the following css :
.loadingDiv {
float: left;
display: none;
height: 26px;
width: 60px;
background: url("images/animations/ajaxLoader.gif") no-repeat;
background-position: center center;
}
Then changed the javascript like this :
function ValidateFormAndAjaxSubmit(formId, callingElement) {
if (IsNotDblClick(callingElement.id)) {
var _form = $("#" + formId);
var validator = _form.validate();
var anyError = false;
anyError = !_form.valid();
if (anyError) {
window.latestClick = '';
return false; // exit if any error found
}
$('#' + callingElement.id).hide();
$('#loadingDiv_' + callingElement.id).show();
$.post(_form.attr("action"), _form.serialize(), function (data) {
$('#loadingDiv_' + callingElement.id).hide();
$('#' + callingElement.id).show();
if (data.success && data.redirectUrl.length > 0) {
window.location.href = data.redirectUrl;
}
else {
var isValid = validateResponse(_form, data);
window.latestClick = '';
}
})
}
}

Related

Unable to reset the data form

Unable to reset the data in jQuery. I am trying to save the data using jQuery its happening. But when I click on remove glyph-icon, data is not reset in the form. I tried a code but it is not working. When I click on remove icon also the data is being saved. I am stuck with place the reset code. Used glyphicons to save and reset the data. I do not wish do abort in ajax.
//Banking details form validation
$(document).ready(function() {
$('.editBankDetailBtn').click(function() {
if ($('.editBankDetail').is('[readonly]')) { //checks if it is already on readonly mode
$('.editBankDetail').prop('readonly', false); //turns the readonly off
$('.editBankDetailBtn').html('<span class="glyphicon glyphicon-floppy-disk"> </span>' + '<span id="reset-form" class="glyphicon glyphicon-remove"> </span>');
// $('.glyphicon-remove')[0].reset();
} else { //else we do other things
var patt = /^([0-9]{11})|([0-9]{2}-[0-9]{3}-[0-9]{6})$/;
var reg = /^[A-Za-z]{4}[0-9]{6,7}$/;
patt.test('acdbdfdsfsf22-333-666666'); // true
var bname_1 = document.getElementById('bankName').value;
if (bname_1 == "") {
document.getElementById('bankName').style.borderColor = "red";
return false;
} else {
document.getElementById('bankName').style.borderColor = "#cccccc";
}
var aaccount_number = document.getElementById('accountNumber');
if (!patt.test(aaccount_number.value)) {
document.getElementById('accountNumber').style.borderColor = "red";
return false;
} else {
document.getElementById('accountNumber').style.borderColor = "#cccccc";
}
var bifsc = document.getElementById('ifscCode').value;
if (!reg.test(ifscCode.value)) {
document.getElementById('ifscCode').style.borderColor = "red";
return false;
} else {
document.getElementById('ifscCode').style.borderColor = "#cccccc";
}
var bank_address = document.getElementById('branchAddress').value;
if (bank_address == "") {
document.getElementById('branchAddress').style.borderColor = "red";
return false;
} else {
document.getElementById('branchAddress').style.borderColor = "#cccccc";
}
$('.editBankDetail').prop('readonly', true);
$('.editBankDetailBtn').html('<span class="glyphicon glyphicon-pencil"> </span>');
}
$(document).ready(function() {
$('.glyphicon-remove').on('click', function() {
$("#reset-form").trigger("reset");
});
});
});
});
function saveBankDetail() {
$.ajax({
url: '${pageContext.request.contextPath}/update-bankdetail.html',
type: "post",
data: {
bankName: $('#bankName').val(),
branchAddress: $('#branchAddress').val(),
accountNumber: $('#accountNumber').val(),
ifscCode: $('#ifscCode').val(),
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You have $(document).ready(...) within $(document).ready(...). Note that the event is only fired once, which means that the inner one is never fired. You have also nested the click events (not recommended).
Your code should be looking something like:
$(document)
.ready(
function() {
$('.editBankDetailBtn').click(function() {
...
};
$('.glyphicon-remove').on('click', function() {
$("#reset-form").trigger("reset");
});
...

Don't allow multiple form submissions

I'm trying to validate Google Captcha and my form, which currently does work. I'm using JQuery Forms and Validate Unobstructive. The problem is after submission, you can still submit the form as many times as you click.
Is there a way to ensure this only happens once?
I have tried using the following (commented in the code), but then you can't submit the form again to recheck the captcha:
if ($form.data('submitted') === true) { } else { }
JS:
$(document).ready(function () {
//Intercept Submit button in order to make ajax call instead of a postback
$('#contactForm').preventDoubleSubmission();
});
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function () {
$("button").click('submit', function (e) {
e.preventDefault();
var $form = $("#contactForm");
$($form).bind("invalid-form.validate", function() {
if( $("invalid-form.validate") ) {
formErrors();
}
})
// if ($form.data('submitted') === true) {
// // Previously submitted - don't submit again
// } else {
if ($form.valid()) {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
if ( captchaCheck() == false) {
captchaCheck();
} else {
// Make ajax call form submission
$.ajax({
url: $form.attr('action'),
type: 'POST',
cache: false,
data: $form.serialize(),
success: function (result) {
success();
}
});
}
}
// }
});
// keep chainability
return this;
};
function hover() {
$(".contour-button").on("mouseenter", function() {
return $(this).addClass("hover");
});
}
function hoverOff() {
$(".contour-button").on("mouseleave", function() {
return $(this).removeClass("hover");
});
}
function success() {
$(".contour-button").addClass("success");
var formFields = $(".contactForm input, .contactForm textarea, .contactForm button");
$(formFields).attr('disabled', 'disabled');
$(formFields).animate({'opacity':'0.5'});
$(".contour-btn-arrow").addClass("contour-btn-success");
$(".contour-button .submit").html("Thank you for your enquiry");
}
function formErrors() {
$(".contour-button").addClass("form-errors").delay(3500).queue(function(){
$(this).removeClass("form-errors").dequeue();
});
$(".contour-btn-arrow").addClass("contour-btn-error").delay(3500).queue(function(){
$(this).removeClass("contour-btn-error").dequeue();
});
$(".contour-button .submit").html("There are errors on the form").delay(3500).queue(function(){
$(this).html("Submit").dequeue();
});
}
function captchaCheck() {
var captchaResponse = grecaptcha.getResponse();
if(captchaResponse.length == 0) {
// html for the captcha error message
var captchaMsgHtml = '<img src="/images/form-error-icon.png" /> Please check the captcha and try again';
$("#captchaMsg").html(captchaMsgHtml).slideDown(500);
$(".g-recaptcha div div").addClass("recaptchaHighlight");
return false;
} else {
$(".g-recaptcha div div").removeClass("recaptchaHighlight")
$("#captchaMsg").hide();
return true;
}
}
hover();
hoverOff();
You might disable clicked button just putting
var that = this;
$(that).attr("disabled", true);
after
e.preventDefault();
then, if you need, enable it when the operation is completed with
//probably after success()
$(that).attr("disabled", false);
I hope that's what you need!
I managed to solve this in a similar way to MonkeyZeus's suggestion by wrapping the AJAX call in a condition, using a bool (true/false).
var ajaxRunning = false;
$("button").click('submit', function (e) {
e.preventDefault();
var $form = $("#contactForm");
$($form).bind("invalid-form.validate", function() {
if( $("invalid-form.validate") ) {
formErrors();
}
})
if ($form.valid()) {
if ( captchaCheck() === false) {
captchaCheck();
formErrors();
} else {
if(!ajaxRunning){
ajaxRunning = true;
$.ajax({
url: $form.attr('action'),
type: 'POST',
cache: false,
data: $form.serialize(),
success: function (result) {
success();
},
error: function (result) {
captchaCheck();
formErrors();
}
});
}
}
}
});
function hover() {
$(".contour-button").on("mouseenter", function() {
return $(this).addClass("hover");
});
}
function hoverOff() {
$(".contour-button").on("mouseleave", function() {
return $(this).removeClass("hover");
});
}
function success() {
var disabledElements = "#formFooter button, .contourField input, .contourField textarea";
var opacityElements = ".contourField input, .contourField textarea";
// disable button & inputs once submitted
$(disabledElements).attr('disabled', 'disabled');
// change opacity of elements
$(opacityElements).animate({ 'opacity' : '0.5' });
$(".contour-button").addClass("success");
$(".contour-btn-arrow").addClass("contour-btn-success");
$(".contour-button .submit").html("Thank you for your enquiry");
}
function formErrors() {
$(".contour-button").addClass("form-errors").delay(3500).queue(function(){
$(this).removeClass("form-errors").dequeue();
});
$(".contour-btn-arrow").addClass("contour-btn-error").delay(3500).queue(function(){
$(this).removeClass("contour-btn-error").dequeue();
});
$(".contour-button .submit").html("There are errors on the form").delay(3500).queue(function(){
$(this).html("Submit").dequeue();
});
}
function captchaCheck() {
var captchaResponse = grecaptcha.getResponse();
if(captchaResponse.length == 0) {
// html for the captcha error message
var captchaMsgHtml = '<img src="/images/form-error-icon.png" /> Please check the captcha and try again';
$("#captchaMsg").html(captchaMsgHtml).slideDown(500);
$(".g-recaptcha div div").addClass("recaptchaHighlight");
return false;
} else {
$(".g-recaptcha div div").removeClass("recaptchaHighlight")
$("#captchaMsg").hide();
return true;
}
}
hover();
hoverOff();
For starters, if you are actually using a <form> with a dedicated <submit> or <button type="submit">Submit</button> then you should be listening for on.('submit'):
var allowSubmit = TRUE;
$('form').on('submit', function(e)
{
if(allowSubmit === TRUE)
{
allowSubmit = FALSE;
// Perform your validations + AJAX calls and make sure to set
// allowSubmit = TRUE; wherever appropriate
if(validationFails)
{
allowSubmit = TRUE;
}
else
{
$.ajax({
url: $form.attr('action'),
type: 'POST',
cache: false,
data: $form.serialize(),
success: function (result) {
success();
allowSubmit = TRUE;
},
error: function() {
// Do some error handling
allowSubmit = TRUE;
}
});
}
}
else
{
e.preventDefault();
}
});

jQuery - preventDefault() in .each function

I want to use preventDefault() in .each function for collection of buttons and its not working. When I use it with one .click function it works fine but inside .each is not
Whan am I doing wrong?
Here is my .js code
$(document).ready(function() {
var findingStatus = $('#findingStatus').attr('finding-status-type');
var findingLike = $('#finding_like_btn');
var findingDislikeBox = $('.finding_dislike_add');
var findingDislikeCollection = $('.finding_dislike_add_btn')
var findingUnlike = $('#finding_unlike_btn');
var findingDislikeRemoved = $('#finding_dislike_removed');
var alertBox = $('.alert-box').hide();
if (findingStatus == 0) {
findingDislikeBox.show();
findingUnlike.hide();
findingDislikeRemoved.hide();
}
else if (findingStatus == 1) {
findingDislikeBox.hide();
findingUnlike.show();
findingDislikeRemoved.hide();
}
else if (findingStatus == 2) {
findingDislikeRemoved.show();
findingUnlike.show();
findingDislikeBox.hide();
findingLike.hide();
}
findingDislikeCollection.each(function() {
var findingDislike = $(this).clone();
var url = findingDislike.attr("href");
findingDislike.click(function(event) {
event.preventDefault();
$.ajax({
url: url,
type: "POST",
dataType: "json",
success: function(data) {
if (data.profileState == 1) {
$('#dislike_count_btn').text('Odrzuć' + data.DislikeCount);
findingDislikeBox.hide();
findingDislikeRemoved.show();
findingUnlike.show();
//findingUnDislike.show();
//findingUnDislike.attr('disabled', false );
//findingUnDislike.text('Cofnij');
}
else {
alertBox.show();
if ($('.alert-box-msg').length==0) {
$('.alert-area').prepend('<p class="alert-area alert-box-msg">Żeby korzystać z tej funkcji musisz być zalogowany.</p>');
}
findingDislike.attr('disabled', false );
}
},
error: function() {
alert('Problem z serwerem, spróbuj ponownie za kilka minut.');
findingDislike.attr('disabled', false );
}
});
});
});
$('html').click(function (e) {
if (!$(e.target).hasClass('alert-area')) {
$('.alert-box').hide();
findingDislike.attr('disabled', false );
}
});
});
Thanks for answer
You are cloning the element with .clone which means you're not actually attaching an event listener to anything in the DOM. Cloned elements must be manually inserted into the DOM with JavaScript for them to have any effect.
This is not a correct way. Following should work:
findingDislikeCollection.click(function(event){
var findingDislike = $(this);
var url = findingDislike.attr("href");
//AJAX call
event.preventDefault();
});
More details on click event are given here:
https://api.jquery.com/click/

Modal backdrop doesn't hide when clicking an element inside it

On a page I have a modal with few <div class="message-container">. If the user clicks on that element, the page sends AJAX request for new modal. But when I close a new modal, I still have the backdrop from the first modal.
All modals return PHP. I have also tried closing the old modal before opening a new one but that still doesn't help.
Here is the JS code:
$(document).on('click', '.message-container', function () {
var messageId = $(this).attr('data-message-id');
$.ajax({
method: "POST",
data: {
action: 'readMessage',
messageId: messageId
}
}).done(function (ret) {
var obj = jQuery.parseJSON(ret);
if (obj.code == 1) {
$('#messages').modal('hide');
$('.modal-container').html('');
$('.modal-container').html(obj.value);
$('#read-message').modal('toggle');
} else {
}
});
});
$(document).on('click', '.unreadedMessages', function () {
$.ajax({
method: "POST",
data: {
action: 'getMessages'
}
}).done(function (ret) {
var obj = jQuery.parseJSON(ret);
if (obj.code == 1) {
$('.modal-container').html(obj.value);
$('#messages').modal('show');
} else {
var content = '<div class="alert alert-danger" id="messages-alert" role="alert">' + obj.value + '</div>';
}
})
});
unreadedMessages is first.
Not sure if this is exactly what you need, but here is a CSS pattern that I used when I have multiple modals open.
body .modalBlockout ~ .modalBlockout {
opacity: 0 !important;
}
This will hide any extra block out elements, and only shows the first one.

My jQuery ajax if/else on click is not working

So I've been stuck at this problem for quite a long time. Basically I have a button (#action) located in index.html. I have a second page : number.html. I'm trying to get in the .receiver span from index.html either .success content or .failure content from number.html, depending if #action was clicked in less than 2 seconds.
Here is the code :
$(function() {
var ajaxRetrieve = function(callback) {
$.ajax({
url: 'number.html',
method: 'POST',
success: function(responseData) {
callback(responseData);
},
error: function(responseData) {
alert('Check yourself');
}
});
}
var flag = 0;
$('#action').on('click', function() {
flag = 1;
});
if (flag == 1) {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.success'));
});
} else {
setTimeout(function() {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.failure'));
});
}, 3000);
};
});
Problem : on click, I never get the .success content, and I have no error message. But after 2 seconds, the .failure actually shows up. I tried several ways to make it work but it doesnt. I also checked if the flag value was changed on click with an alert box, and it was
You need to include the ajax calls within the on click function, otherwise the if logic will only be called when the page is loaded and never again.
$(function() {
var ajaxRetrieve = function(callback) {
$.ajax({
url: 'number.html',
method: 'POST',
success: function(responseData) {
callback(responseData);
},
error: function(responseData) {
alert('Check yourself');
}
});
}
var flag = 0;
$('#action').on('click', function() {
flag = 1;
flagCheck();
});
var flagCheck = function() {
if (flag == 1) {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.success'));
});
} else {
setTimeout(function() {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.failure'));
});
}, 3000);
};
}
});

Categories