How to check if ajax request comes from a button - javascript

Im disabling all buttons when an ajax request is processing and enable them when ajax process is done and succeded. Now my question is... how do I check that the ajax request is comming from an specific element, in this case a button?
here is my code so far:
$(document).ajaxSend(function(){
if(ajax request comes from a button) {
$(':button').prop('disabled', true);
}
});
$(document).ajaxComplete(function () {
errorCount = 0;
$(':button').prop('disabled', false);
});
Any advice will be very appriciated :) Thanks all!

You can try like this :
$(document).ajaxSend(function(sender){
if(sender.tagName == 'button') {
$(sender).prop('disabled', true);
}
});

After lite research and use of the provided advices here I came up with the solution, here is my code now and working:
$(document).on('click', 'button', function () {
var $this = $(this);
$(document).ajaxSend(function(){
$this.prop('disabled', true);
});
$(document).ajaxComplete(function () {
$this.prop('disabled', false);
});

Related

Is possible in on click function in jQuery wait for ajax complete and then do some code?

I want show modal after ajax is complete, here is my code:
$('.mymodalbtn').on('click', function (e) {
modalWindow = $(this).attr('data-target');
// alert(modalWindow);
$(document).ajaxStop(function () {
//0 === $.active
$(modalWindow).modal('show');
});
});
It is possible to do that? Now modal show after every ajax complete.
Thank you.
You can use .ajaxComplete() method of ajax request,which registers a handler to be called when Ajax request is completed.
Read more here.
Use complete event when your ajax call completed.
$('.mymodalbtn').on('click', function (e) {
modalWindow = $(this).attr('data-target');
$.ajax({
type: 'GET',
url: 'your_url',
success: function (responseData, textStatus) {
},
complete: function (textStatus) {
$(modalWindow).modal('show');
},
error: function (responseData)
{
}
});
});
I'm not sure about the way you're doing an ajax call, but I've been able to do it with the post super global
$_post(phpfile.php, $_post(phpfile.php, {variables to send}, function) you can use data as a parameter for the function and it will be anything that PHP echoes including error messages
Thank you for inspiration finally I do it this way.
global variable:
window.modal = "";
on click function:
$('.mymodalbtn').on('click', function (e) {
modalWindow = $(this).attr('data-target');
window.modal = modalWindow;
});
and ajax complete:
$(document).ajaxComplete(function (event, request, settings) {
if(window.modal != ""){
$(window.modal).modal('show');
window.modal = "";
}
});
Hope it is allright :-)
try to use setTimeout.
setTimeout(function(){
$('#mymodal').modal('show');
},4000);
Yes it is possible. You can use .ajaxStop() or .ajaxComplete() or in .ajaxSuccess()

JQuery Prevent Function .click Firing On Every Click

When I click a chat on my site I want the messages to be grabbed from the server so I use an $.post request like so :
$("#friendsDiv").on("click", "#aFriend", function(event){
retrieveMessages();
}
and this is what is in the retrieveMessages function
$.post("PHP/chat.php",
{
action:'retrieveMessages',
last_message: last_message,
conversation_id:conversation_id
},
function(data){
$("#messages").append(data);
last_message = $("#messages").find(".aMessage:last").attr("id");
$("#messages").animate({ scrollTop: $("#messages")[0].scrollHeight}, 1000);
}
);
The issue is that if the button is clicked very quickly multiple post requests will begin before the last_message is updated, this results in many copies of the same messages being displayed. Is there a way to prevent the button being clicked quickly or stop the post request being processed if another of the same request is already being processed?
EDIT
The #aFreind element is a DIV not a button
Typically in such situation you just disable a button until request is complete. For this you will need to provide a callback function. For example:
$("#friendsDiv").on("click", "#aFriend", function (event) {
// reference the button
var button = this;
// disable the button
this.disabled = true;
// provide a callback to be invoked when post is done
retrieveMessages(function() {
button.disabled = false;
});
});
function retrieveMessages(callback) {
$.post("PHP/chat.php", {
action: 'retrieveMessages',
last_message: last_message,
conversation_id: conversation_id
}, function (data) {
$("#messages").append(data);
last_message = $("#messages").find(".aMessage:last").attr("id");
$("#messages").animate({
scrollTop: $("#messages")[0].scrollHeight
}, 1000);
// execute callback which enables button again
callback();
});
}
Demo: http://jsfiddle.net/9t8fLdjn/
Your best bet would be to disable the button and then enable it after $.post
$("#friendsDiv").on("click", "#aFriend", function(event) {
$(this).prop('disabled', true); // disable
retrieveMessages();
});
and the retrieveMessage function
$.post("PHP/chat.php", {
action: 'retrieveMessages',
last_message: last_message,
conversation_id: conversation_id
}, function(data) {
$("#messages").append(data);
last_message = $("#messages").find(".aMessage:last").attr("id");
$("#messages").animate({
scrollTop: $("#messages")[0].scrollHeight
}, 1000);
$(this).prop('disabled', false); // enable it again
});
Instead of using on you could use the one jQuery function and bind the button again in the callback. Se http://api.jquery.com/one/
$("#friendsDiv").one("click", "#aFriend", retrieveMessages });
var retrieveMessages = function(){
$.post("PHP/chat.php", {
...
}).done(function(){
$("#friendsDiv").one("click", "#aFriend", retrieveMessages });
});
};

add ajaxStart and ajaxStop with $("body").on()

I'm trying to take away the ability to submit a form when an ajax call is in process (it is a long query and I don't want it submitted again while it is being initially made.) However I seem to be attaching it incorrectly.
$(function(){
$("body").on("click", "#process", function(){
submit_form();
});
$("body").on("ajaxStart", "*", function(){
$("body").off("click", "#process", submit_form);
alert("test");
var div = $("<div>", {
id: "loading",
html: "Working"
}).prependTo("body");
});
$("body").on("ajaxStop", "*", function(){
alert("done");
$("#loading").remove();
});
});
I'm not seeing either the div being attached or the alerts being fired. I feel like there may be an issue with the * selector within my on() statements. I don't know though. I've tried to attach the ajaxStart with on so that $("#loading") which is dynamically added, can be removed.
I would do something more along the lines of setting a variable to allow/disallow the AJAX call:
var processing = false;
$('form').on('submit', function(e){
e.preventDefault();
if(processing === false){
processing = true;
// allow AJAX here
$.ajax({
url: 'sample.com/process',
type: 'POST',
complete: function(){
processing = false;
}
});
}
});

Postmessage in jQuery

I send data using Postmessage, but to get them right is not obtained.
My attempts:
Variant 1:
window.addEventListener("message", function(event) {
console.log(event.data);
}, false);
Variant 2:
$.bind("message", function (data) {
console.log(data);
}, false);
First variant works, but is not used jQuery. Show you how to use jQuery in this situation?
if needed sending code::
$(function() {
var iframe = $('iframe#someFrame');
setTimeout(function() {
iframe[0].contentWindow.postMessage('message to localhost', '*');
}, 1000);
});
You need to grab the originalEvent from jQuery:
$(window).on("message", function(e) {
var data = e.originalEvent.data;
});

How to change html class after ajax successful response?

I want to toggle the voting arrow class, the same way as stackoverflow's voting arrow. For a logged in user, if already voted up, the html is:
After user clicked down arrow, if response success, How to change "vote-up-on" to "vote-up-off", and change "vote-down-off" to "vote-down-one"?
Well, this works the same as the SA votes - it could be a bit more concise but I really need to get back to work ;-)
vote up
<span class="votes">0</span>
vote down
and the jquery:
$(document).on('click', '.vote-up', function () {
if(!$(this).hasClass('vote-locked')){
var votes = parseInt($(this).parent().find('.votes').text());
if(!$(this).hasClass('vote-off')){
$(this).addClass('vote-off');
$(this).nextAll('a').addClass('vote-locked');
votes++;
}
else{
$(this).removeClass('vote-off');
$(this).nextAll('a').removeClass('vote-locked');
votes--;
}
$(this).parent().find('.votes').text(votes);
}
});
$(document).on('click', '.vote-down', function () {
if(!$(this).hasClass('vote-locked')){
var votes = parseInt($(this).parent().find('.votes').text());
if(!$(this).hasClass('vote-off')){
$(this).addClass('vote-off');
$(this).prevAll('a').addClass('vote-locked');
votes--;
}
else{
$(this).removeClass('vote-off');
$(this).prevAll('a').removeClass('vote-locked');
votes++;
}
$(this).parent().find('.votes').text(votes);
}
});
http://jsfiddle.net/gqDgL/
Make a callback function when you receive Ajax response.
function addVoteUpClass() {
if (jQuery(".vote").hasClass("vote-up-on")) {
jQuery(".vote-up-on").removeClass("vote-up-on").addClass("vote-up-off");
}
}
jQuery.ajax({
url: "your_url",
method: "GET",
success: function(data) {
addVoteUpClass();
}
});
jQuery can add and remove classes, using addClass and removeClass,
$('#vote-up-%1$d').removeClass('vote-up-on');
$('#vote-up-%1$d').addClass('vote-up-off');
$("#vote-up").click(function () {
$(this).toggle();
$(this).toggleClass("vote vote-down-off");
});
try this

Categories

Resources