jQuery Allow only one click before .ajax() - javascript

I am trying to allow a button to be clicked only once and then some data be submitted via ajax. The problem I am facing is that a user can click 50x and the data is POST submitted each time ?
jQuery("#id").unbind('click');
jQuery.ajax({
type: "POST",
url: ajax_url,
data: ajax_data,
cache: false,
success: function (html) {
location.reload(true);
}
});
How can I ensure that if a user clicks #ID 100x - that the data is only submitted once ? And then #ID is re-enabled ?

You could use the .one() function in jQuery.
jQuery("#id").one('click', function()
{
jQuery.ajax({
type: "POST",
url: ajax_url,
data: ajax_data,
cache: false,
success: function (html) {
location.reload(true);
}
});
});
Bear in mind this will completely remove the click event, even if you have an error with your ajax, you still won't able to click it again.

just disable the button
$("#id").attr("disabled", "disabled")
and then in the success function enable it
$("#id").removeAttr("disabled")

Easiest way would be to use a flag which gets reset when the success is fired:
if(clicked == False){
clicked = True;
jQuery("#id").unbind('click');
jQuery.ajax({
type: "POST",
url: ajax_url,
data: ajax_data,
cache: false,
success: function (html) {
location.reload(true);
clicked = False;
},
error: function () {
alert("Error happened");
clicked = False;
}
});
}

You can disable to control, or use one of the many modal libraries to show the spinning wheel
see this Jquery modal dialog question on SO

You could disable the button on click event and enable it back when ajax request is completed.

In your click event you could disable the button and then re-enable the button in the success function of the ajax event.
Another option would be to set a parameter on the element that is being clicked to indicate the button was clicked and then check to see if it is set if it is don't send the ajax request if not then do send it. Once the ajax is done you can unset the parameter again to allow it to be run.

try this:
$(document).ajaxStart({ function() {
$('#submit_button').click(function(){
return false;
});
});
where: #submit_button is id of the element U want to disable
that code will disable clicking on the submit button

Related

Success message fades out after first form submit but not after subsequent submits

The first time a submit form the success message displays and then fades correctly. If I submit form again then it doesn't work. I want it to repeat the display of message and subsequent fade out after each form submit.
I found this answer
Trying to have a JQuery flash message after an ajax from submit in show again after more than one form submit (in rails)
but couldn't get to work, I'm very new to all this so be gentle ;-)
$(document).ready(function() {
$("#editMember").submit(function(e) {
e.preventDefault();
$.ajax( {
url: "php/adminUpdateMember.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
$("#message").text(strMessage);
}
});
});
setTimeout(function() {
$('#message').fadeOut('fast');
}, 4000);
});
Your setTimeout() call is not inside your submit() block. It will trigger the fadeOut 4 seonds after page load, and not be called again.
You might also need to call $('#message').show(), to make the element visible after it's been faded out.
$(document).ready(function() {
$("#editMember").submit(function(e) {
e.preventDefault();
$.ajax( {
url: "php/adminUpdateMember.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
$("#message").text(strMessage);
$('#message').fadeIn('fast');
}
});
setTimeout(function() {
$('#message').fadeOut('fast');
}, 4000);
});
});

Disable button link on beforeSend ajax

I have a button link on my view like so:
Go Somewhere
Now, I am using ajax on my page to submit values to my webApi controller methods, and when I do, I would like the button link to be disabled. Here is my ajax:
$.ajax({
url: myUrl,
method: "DELETE",
beforeSend: function () {
disableSendButton();
},
success: function() {
row.remove();
toastr.options = {
onHidden: function () {
window.location.href = redirectUrl;
},
timeOut: 2000
}
toastr.success("Success.");
}
});
function disableSendButton() {
$("#My-Btn").addClass("ui-disabled");
}
This does not work for me. The button is still active during ajax call. How do I disable this button during ajax call?
Use
$("#My-Btn").prop('disabled', true).addClass("disabled");
And add CSS
.disabled{
cursor: not-allowed;
}
This will put a disabled cursor on your button.
can you try this .attr("disabled", "disabled"); on your button

How to avoid ajax async when using jQuery events

I have an input field with ajax call (filling some other input fields) on blur and buttons with click events (some of the click events set input fields to an empty string).
For example,
$("#input_field1").on('blur', function () {
$.ajax({
//async:false,
method: "GET",
url: "my_ajax.php",
cache: false,
dataType: "json",
data: { data1: $("#input_field1").val()},
success: function(result){
$("#some_other_input").val(result.data2);
}
})
});
$("#button1").on('click', function () {
$("#input_field1").attr("readonly", true);
var form = $("#my_form");
form.validate().resetForm();
form[0].reset();//form contains #some_other_input
});
When that input field is focused and then user clicks on any button, blur event is triggered and of course, appropriate click event after it.
If I don't use async:false, ajax will fill those input fields after click event is processed and other inputs will be filled instead of being empty.
Reading about how async:false should be avoided always, I need a way for my click events to wait until ajax is done, if there is an ajax call at that moment.
You need a concurrency check for your cases. On your blur action; check and set a value to prevent reentering the other calls.
Also during an ajax request, you need to prevent clicking the buttons.
One more thing, what if just after bluring your input field, user re-focuses and re-focusouts your input? In this case, your action will be triggered twice.
As a result, you need to handle concurrency. There are also some javascript libraries to handle concurrency, you can either use them or handle by your own.
Anyway to handle your case, here is a sample code:
let hasCall = false;
$("#input_field1").on('blur', function () {
if(hasCall){
return; //there is an active call...
}else{
hasCall = true;
$("#button1").prop('disabled', true);//prevent clicking on button
}
$.ajax({
//async:false,
method: "GET",
url: "my_ajax.php",
cache: false,
dataType: "json",
data: { data1: $("#input_field1").val()},
success: function(result){
$("#some_other_input").val(result.data2);
}
}).always(()=>{
//reset the state:
hasCall=false;
$("#button1").prop('disabled', false);
});
});
$("#button1").on('click', function () {
$("#input_field1").attr("readonly", true);
var form = $("#my_form");
form.validate().resetForm();
form[0].reset();//form contains #some_other_input
});

Submit a link using javascript or jquery without refreshing a page

I have a link which invokes an API which saves a session. Suppose my API be present on http://www.example.net and my link is as below :
<a href="http://www.example.net" >Click here </a>
Now i don't want to refresh the page. Just use JQuery or Javascript to simply execute the link and give an alert like "Action Succesfull". I don't see the point of using AJAX as I don't require any database actions from my side. Thanks
The point of AJAX is not to do database actions, its to comunicate with the server without needing to reload the page. I think your description qualifies for the use of AJAX, since you do expect a answer from the server, and you do not want to reload the page.
You could also open a iframe, or a new window, but ajax might be the solution here.
Keep in mind you need to cancel that event when you click on the anchor.
So, with ajax you could so something like:
$('a').on('click', function(e) {
e.preventDefault;
var href = this.getAttribute('href');
$.ajax({
url: href,
success: function(text) {
alert(text);
}
});
});
You will need an ajax call. Something like this:
$.ajax({
cache: false,
type: "Post",
url: "http://www.example.net",
success: function () {
alert("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
},
finaly: function () {
alert("Finish");
}
});
You can simply use onclick event if you don't want to use AJAX
Click here
Try to use an ajax call when click on button submit or the link. Here is the code :
$("a").click(function(e){
$.ajax({
url: "http://www.example.net",
type: "POST",
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(data,textstatus,jqXHR)
{
alert("Success");
}
});
e.preventDefault();
});
you need to do something like this:
$('a').click( function(e) {
e.preventDefault();
var url = "your link";
$.ajax({
url: url,
success: function(data)
{
alert(data); // show response.
}
});
return false;
});

unbind event handlers while ajax in progress

I have a text field with keypress event handler jsfiddle. And when I type something in this field and press "Enter" 2 times, 2 requests will be send. I want to turn off all events, while ajax request in progress. One option is to call .off() function before ajax call, and then bind event handler again. Any other options?
use the callback handlers from your ajax call and a boolean used as flag. By setting the ajaxLoading boolean to false in the "always" callback, you can be sure that other, future requests can be made independent from whether the current ajax call throws an error or not.
var ajaxLoading = false;
if(!ajaxloading){
ajaxloading=true;
$.ajax({
url: 'your url',
type: 'GET',
dataType: 'JSON'
})
.done(function(data) {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
ajaxloading=false;
});
}
I use 2 boolean flags, like:
var is_requesting = false, should_request = false;
function onkeydown() {
if (is_requesting) {
should_request = true;
return;
}
is_requesting = true;
$.ajax({}, function () {
is_requesting = false;
if (should_request) {
onkeydown();
}
});
}
Is there a good reason for you not to use the jQuery .off() function?
If so then you could simply disable the control prior to making the ajax request and re-enable it once the request is complete. This would also stop the user from thinking he/she could change the result by changing the text value during the request.
//Disable the input
$('#myresult').prop('disabled', true);
$('#myresult').append('<br>'+$(this).val());
$.ajax({
type: "POST",
beforeSend: function() {},
complete: function() {
//Re-Enable the input
$('#myresult').prop('disabled', false);
},
url: "/echo/json/",
data: { delay : 3 },
success: function(){},
error: function() {},
dataType: 'json'
});

Categories