Ajax Checkbox that submit with prevent click upon post/submit - javascript

Hi I'm working on an ajax function in jquery that saves the value of a checkbox. Here is my question, What if the user clicks in multiple times even the saving is not yet finished/success? How can i Prevent the user to tick the checkbox when the form is submitting? Thanks !
Heres my Code Snippet:
$(".chkOverride").click(function (e) {
var userId = $("#UserId").val();
var isChecked = $(this).is(":checked")
$.ajax({
url: "/Worker/Worker?Id=" + Id + "&isChecked=" + isChecked + "&UserId=" + UserId,
type: "post",
success: function (result) {
alert("Success!");
location.reload();
},
error: function () {
}
});
});

You can disable the checkbox before starting the ajax call. You may use the prop() method to do that. Set the disabled property value to true
$(".chkOverride").click(function (e) {
var _this=$(this);
_this.prop('disabled', true);
var userId = $("#UserId").val();
var isChecked = $(this).is(":checked")
$.ajax({
url: "/Worker/Worker?Id=" + Id + "&isChecked=" +
isChecked + "&UserId=" + UserId,
type: "post",
success: function (result) {
alert("Success!");
//No point in enabling as you are going to reload the page
_this.prop('disabled', false);
location.reload();
},
error: function () {
alert("Error :(");
_this.prop('disabled', false);
}
});
});

Have you come across this link:
Inhibit a checkbox from changing when clicking it
You can disable the checkbox using
$this.attr('disabled', 1);
Disable the button before making the Ajax call.

Related

jQuery prevent submit of form inside of if statement

Sorry if there are some mistakes, but I am a total noob and I am also posting for the first time on StackOverflow.
I am trying to configure a submit form, that controls if the inserted PIN is right, and if so goes on with the submission. I did some online research and found out that with jQuery we can use to function event.preventDefault(), I tried to insert it inside my AJAX request but it looks like it doesn't stop the form from being saved.
The code looks like these:
function verifyOTP() {
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp" : otp,
"PIN" : PIN,
"action" : "verify_otp"
};
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
},
error : function() {
alert("ss");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
error : function(event) { event.preventDefault(); };
}
//if I insert "return false;" here the submit is always blocked
}
I checked on atom if the parenthesis are right and it looks like it is.
Any ideas how I should use the preventDefault()?
I also checked if the output of m_ajaxpinr.php is correct, and it is. I also tried like these but it still didn't work...
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
$("form").submit(function(event) {
if (response.type == 'success')
{
alert(response.type);
}
else if (response.type == 'error')
{
alert(response.type);
event.preventDefault();
}
});
as said in comment above ajax call is asynchronous, you need to complete cancel default action for the form or put event.preventDefault(); on the top function, then submit it in success function if it valid otp.
.val() will not return null, it return empty if no input.
$('#myForm').on('submit', verifyOTP);
function verifyOTP(e) {
e.preventDefault(); // note this
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp": otp,
"PIN": PIN,
"action": "verify_otp"
};
if (otp) { // mean not null, undefined, empty, false, 0
$.ajax({
//url: 'm_ajaxpinr.php',
url: 'https://httpbin.org/anything/test',
type: 'GET',
dataType: "json",
data: input,
success: function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
if(response.args.otp == 1234){
console.log('valid otp, continue submission')
$('#myForm').off('submit'); // remove submit event
$('#myForm').submit(); // then submit the form
}
else{
console.log('invalid pin,\nvalid pin: 1234');
}
},
error: function() {
console.log("server error, submission cancelled");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
console.log("otp maybe empty, submission cancelled");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<input id="contomovimentato">
<button>submit</button>
</form>

jQuery How to make a variable that shows just the value of a form array

So right now I have a form that is saved in AJAX when submitted.
$(document).ready(function () {
$("#dispatchForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr("action") || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
$("#form_output").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
I then have it where the result is shown in a variable and put into a textbox on the page when the submit button is clicked, via this code.
$(function () {
$("#dispatchSumbit").on("click", function () {
var text = $("#textarea");
var local = $("#dispatchForm").serialize();
text.val(text.val() + time +" - Dispatched to \n" + local);
});
});
However it shows the whole array which is like this:
I want it to just say "[Time] - Dispatched to Test"
Thanks for the help in advance!
$("#dispatchForm").serialize() is for creating a name=value&name=value&... string for all the inputs in the form, which can be used as the data in an AJAX request. If you just want a single value, use
var local = $("#dispatchForm [name=dispatchLocal]").val();

Only send post/get if form values has changed

I want to prevent multiple ajax calls (user holds enter key down or multi presses submit or other)
I'm thinking, the best way is to use a var with the previous form post values and compare them at each click/submit.. Is it the same? : Then do nothing
But I don't know how to go about it
Here is my javascript/jquery:
$('form').submit(function() {
$theform = $(this);
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
Not very creative with naming vars here:
var serial_token = '';
$('form').submit(function() {
$theform = $(this);
if ($(this).serialize() === serial_token) {
console.log('multiple ajax call detected');
return false;
}
else {
serial_token = $(this).serialize();
}
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
You could combine this with a timeout/interval function which aborts the submit, but the code above should just compare the data in the form
If you have some kind of submit button, just add a class 'disabled' to it when you start the ajax call, and check if it is present before trying to make the call. Remove the class when the server gives a response. Something like:
...
$theform = $(this);
$button = $theform.find('input[type=submit]');
if ($button.hasClass('disabled')) {
return false;
}
$button.addClass('disabled');
$.ajax({
....
},
complete: function () {
$button.removeClass('disabled');
}
});
...

How to manage an event unload

I want to insert in my page an event that trigger when the window close or change except that in the case that has been triggered by a submit button of a particular submit which bring in an analogus page. I tried the follow but it doesn't work. (prova is the name of submit).
$(window).bind("unload", function (event) {
alert('1');
if (event.target.tagName != "prova") {
alert('2');
var postData = {
'chat_message': "I left"
};
$.ajax({
type: "POST",
dataType: "json",
url: base_url + "chat/ajax_add_message/" + chat_id + "/" + user_id,
data: postData,
success: function (data) {
get_messages();
}
});
}
});
Do you really have HTML element with tag "prova" ?
event.target.tagName != "prova"
Maybe you need to check className or id?

jquery on() not registering first click

I am having strange behaviour when using jquery.on().
Basically, just trying to create a newsletter signup form (can be dynamically generated and not there on initial DOM load) and pass the details through in Ajax but it is not registering the first click on the submit button meaning that to successfully submit, the user has to click twice (only seeing the success message and 'subscribe' post on 2nd click).
The html:
<div class="newsletter-widget grid-item masonry-brick">
<input name="Email" type="email" placeholder="Please enter your email" required />
<input type="submit" value="Subscribe" class="newslettersubmit"/>
and the javascript (in document ready);
var newsletterFocus = $('.newsletter-widget').find('input[type=submit]');
$(document).on('submit', newsletterFocus, function (e) {
e.preventDefault();
var newsletterLinks = newsletterFocus;
DD.newsletter.behavior(newsletterLinks);
});
and the functions within an object that are called;
DD.newsletter = {
behavior: function (item) {
item.click(function (e) {
e.preventDefault();
var where = $('.newsletter-widget').find('input[type=submit]').parents('section').attr('id');
var email = $(this).siblings('[name$=Email]'),
emailVal = email.val();
DD.newsletter.subscribe(email, emailVal, where);
});
},
subscribe: function (self, email, where) {
$.ajax({
type: "POST",
data: '{"email":"' + email + '", "method":"' + where + '"}',
url: '/Subscriber/Subscribe',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
self.val(response);
},
failure: function (msg) {
self.val(msg);
}
});
},});
I've tried using 'click' as the action for on() but this registers an event on each click and i get thousands of forms submitted!
Any help appreciated!
Change the div container to a form element:
<form class="newsletter-widget grid-item masonry-brick">
You'll want to register the submit event to the form, not the input field. Here's a quick refactor of your form submission:
$(document).on('submit', '.newsletter-widget', function (e) {
e.preventDefault();
DD.newsletter.behavior(); //Submit the form via AJAX
});
If you wanted to hook this up to your behavior method, just unwrap the click:
behavior: function () {
var where = $('.newsletter-widget').find('input[type=submit]').parents('section').attr('id');
var email = $(this).siblings('[name$=Email]'),
emailVal = email.val();
DD.newsletter.subscribe(email, emailVal, where);
}
The first click on the button will cause the behaviour click event handler to be bound to the button. Bind the behaviour directly instead of in the click event handler.
Replace this:
var newsletterFocus = $('.newsletter-widget').find('input[type=submit]');
$(document).on('submit', newsletterFocus, function (e) {
e.preventDefault();
var newsletterLinks = newsletterFocus;
DD.newsletter.behavior(newsletterLinks);
});
with:
DD.newsletter.behavior($('.newsletter-widget input[type=submit]'));
It should probably (I think) be something like this:
DD.newsletter = {
behavior: function (item) {
var where = $(item).parents('section').attr('id');
var email = $(item).siblings('[name$=Email]'),
var emailVal = email.val(); // why were you declaring this without 'var'?
DD.newsletter.subscribe(email, emailVal, where);
},
subscribe: function (self, email, where) {
$.ajax({
type: "POST",
data: '{"email":"' + email + '", "method":"' + where + '"}',
url: '/Subscriber/Subscribe',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
self.val(response);
},
failure: function (msg) {
self.val(msg);
}
});
},});

Categories