Javascript onclick change button text for a few seconds - javascript

Trying to change the text on a button to processing for a few seconds when it is click
<div id="send"></div>
<button id="button">Send</button>
<script>
$(document).on("click", "#button", function() {
var Path = $('#send').html();
var success = function() { alert("Successful"); };
var error = function(message) { alert("Oopsie! " + message); };
</script>

You're close, you just need to do this $('#button').html("Processing");
Then in the success and error functions, you'll probably want to modify the button text to something else so that it no longer displays "Processing".

This is what you are probably looking for:
$(document).on("click", "#button", function() {
var defaultBtnValue = $('#send').html();
$('#send').html("Processing...");
$.ajax({
url: your_url,
type: "GET",
success: function() {
alert("Successful");
},
error: function(message) {
alert("Oopsie! " + message);
},
complete: function() {
$('#send').html(defaultBtnValue);
}
});
});
I'm assuming you wan't this "Processing" to show while something is.. well, processing, like doing an ajax call (this may be a setTimeout function as well). Good practice is to first save the default value of the button and make sure to reset it once an action is complete (succes or not) in case something goes wrong.

Related

Jquery timeout for doubleclick

I have a clickable div which should first present a text instruction to tap again in order to fire ajax action, which is under a new class name added after a 1st click. This text has a timeout and will change back to the original.
The problem is that once the text is back to original the actual ajax fire action should stop working as well, but the actual class is not removed. Any suggestions?
What I really need is a kind of doubleclick with a 2second timeout..
function onlyfire() {
$(".onlyfire").click(function() {
var div = $(this);
var original = $(this).html();
div.html("Tap again");
$(".onlyfire").addClass("fire");
setTimeout(function() {
$(div).html(original);
$(".onlyfire").removeClass("fire");
}, 2000);
$(".fire").click(function(fire) {
$.ajax({
type: "POST",
data: dataString,
url: "something.php",
cache: false,
success: function(html) {
div.html(html);
}
});
});
return false;
});
};
<div class="onlyfire">
Do Something
</div>
here is the jsfiddle:
https://jsfiddle.net/jngqzw7q/1/
You could just use an if statement inside the click handler to see whether it is the first or second click (by checking the class), and perform the appropriate action:
function onlyfire() {
$('.onlyfire').click(function() {
var div = $(this);
if (div.is('.fire')) { // second click
alert("this is showing only when the text is 'Tap again'");
} else { // first click
var original = $(this).html();
div.text("Tap again");
div.addClass("fire").removeClass('.onlyfire');
setTimeout(function(){
$(div).html(original);
$(".onlyfire").removeClass("fire");
}, 2000);
}
return false;
});
};
onlyfire();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="onlyfire">
Do Something
</div>
Note: Setting a click handler inside an event handler for another click is not always that good an idea.
You can use .one() with event namespace as parameter, .off() referencing event namespace
function handleClick(e) {
var div = $(this).data("original", this.innerHTML);
// var original = div.html();
div.html("Tap again");
$(".onlyfire").off("click").addClass("fire");
// http://stackoverflow.com/questions/39057179/why-is-click-event-attached-to-classname-fired-after-classname-is-removed#comment65464000_39057261
var fire = $(".fire");
fire.one("click.fire", function() {
alert("this should not be showing once the text is changed back to original");
});
setTimeout(function() {
fire.off("click.fire");
div.removeClass("fire")
.html(div.data("original")).click(handleClick);
}, 2000);
}
function onlyfire() {
$(".onlyfire").click(handleClick);
};
onlyfire();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="onlyfire">
Do Something
</div>

Ideas for mutiple ajax responds for remove loading flag in complete on click

I have this click handler which has an ajax call to get back some data and I set a flag in before send and clears it in complete. The problem that I am facing is that. When I tired to click this twice, the process goes like the following. I wondered what would be a better way to solve this issue. I thought about doing $.active to find out the numbers of ajax calls that's active but that doesn't seem like that right way
1 remove initiated, set flag,
2 remove initiated, set flag.
1 remove response completed, reload and clear the flag.
2 remove response completed, reload (Since the flag was clear by the 1 response, it adds the default which I don't want ).
$(document).on('click', '#remove', function () {
$.ajax({
type: 'POST',
url: '/remove'
data: {
fruits: $(this).val()
},
beforeSend: function () {
$('#fruit-table').addClass('loading');
},
success: function (data) {
loadFruitTable(data);
},
complete: function () {
$('#fruit-table').removeClass('loading');
}
};
loadFruitTable = function (data) {
$('#fruit-table').html(data);
if ($('.processing').length) {
preLoadDefault();
}
};
Just an idea: disable the remove button on click and enable it in the complete-part?
You could use .ajaxStart to show the loading object and .ajaxComplete to handle the event of all data being loaded:
$( document ).ajaxStart(function() {
$( ".log" ).text( "Triggered ajaxStart handler." );
});
$( document ).ajaxComplete(function() {
$( ".log" ).text( "Triggered ajaxComplete handler." );
});
http://api.jquery.com/ajaxComplete/
$(document).on('click', '#remove', function () {
var $fruitTable = $('#fruit-table');
if ($fruitTable.hasClass('loading')) {
return;
}
$fruitTable.addClass('loading');
$.ajax({
type: 'POST',
url: '/remove'
data: {
fruits: $(this).val()
})
.then(loadFruitTable, function () {})
.then(reinitFruitTableStatus);
};
var reinitFruitTableStatus = function () {
$('#fruit-table').removeClass('loading');
};
loadFruitTable = function (data) {
$('#fruit-table').html(data);
if ($('.processing').length) {
preLoadDefault();
}
};
If the element #fruit-table is not dynamically created, you should store it once in a variable available in the whole code above.
Actually... Instead of adding a class, I added a count which increments in beforeSend and decrement in complete. So that way, i can always check if there is any process that's active.

AJAX jQuery on click dynamically created only works first time

I am trying to create a dropdown menu that I dynamically insert into using jQuery. The objects I'm inserting are notifications, so I want to be able to mark them as read when I click them.
I have an AJAX call that refreshes the notifications every second from the Django backend.
Once it's been refreshed, I insert the notifications into the menu.
I keep an array of the notifications so that I don't create duplicate elements. I insert the elements by using .append(), then I use the .on() method to add a click event to the <li> element.
Once the click event is initiated, I call a function to .remove() the element and make an AJAX call to Django to mark the notification as read.
Now my problem:
The first AJAX call to mark a notification as read always works. But any call after that does not until I refresh the page. I keep a slug value to identify the different notifications.
Every call I make before the refresh uses the first slug value. I can't figure out why the slug value is tied to the first element I mark as read.
Also, if anyone has a better idea on how to approach this, please share.
Here's my code:
var seen = [];
function removeNotification(elem, urlDelete) {
elem.remove();
console.log("element removed");
$.ajax({
url: urlDelete,
type: 'get',
success: function(data) {
console.log("marked as read");
},
failure: function(data) {
console.log('failure to mark as read');
}
});
}
function insertNotifications(data) {
for (var i = 0; i < data.unread_list.length; i++) {
var slug = data.unread_list[i].slug
var urlDelete = data.unread_list[i].url_delete;
if (seen.indexOf(slug) === -1) {
var elem = $('#live-notify-list').append("<li id='notification" +
i + "' > " + data.unread_list[i].description + " </li>");
var parent = $('#notification' + i).wrap("<a href='#'></a>").parent();
seen.push(slug);
$( document ).ready(function() {
$( document ).on("click", "#notification" + i, function() {
console.log("onclick " + slug);
removeNotification(parent[0], urlDelete);
});
});
}
}
}
function refreshNotifications() {
$.ajax({
url: "{% url 'notifications:live_unread_notification_list' %}",
type: 'get',
success: function(data) {
console.log("success");
insertNotifications(data);
},
failure: function(data) {
console.log('failure');
}
});
}
setInterval(refreshNotifications, 1000);
I really don't know what do you mean with parent[0] in
removeNotification(parent[0], urlDelete);
I think you can simply try $(this)
removeNotification($(this), urlDelete);
but to be honest I find to put
$( document ).ready(function() {
$( document ).on("click", "#notification" + i, function() {
console.log("onclick " + slug);
removeNotification(parent[0], urlDelete);
});
});
inside a loop .. its bad thing try to put it outside a function and use it like
$( document ).ready(function() {
setInterval(refreshNotifications, 1000);
$( document ).on("click", "[id^='notification']", function() {
console.log("onclick " + slug);
removeNotification($(this), urlDelete);
});
});
and try to find a way to pass a urlDelete which I think it will be just one url

Call jquery function when one function completes

So I have a jquery click function assigned to an on/off toggle. Very simple script:
$('.on-off').on('click', function(e) {
e.preventDefault();
var $this = $(this);
$this.find('.slider').toggleClass('active');
});
We have two versions of this toggle. One toggles instantly when clicked and then we submit the value when clicking next(aka submit).
Our other one calls a jquery ajax function that toggles on success and upon success if it is a specific message code that is defined on the backend.
jQuery.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: {'requestType': requestType},
success: function(message) {
if(message.STATUS=='2000'){
if(currentButtonClicked=='dashboardChargingButton'){
if($('#dashboardChargingButton').html()==startCharge)
$('#dashboardChargingButton').html(stopCharge);
else
$('#dashboardChargingButton').html(startCharge);
}
if(currentButtonClicked=='invokeChargingButton'){
$( "#invokeChargingButton .slider" ).toggleClass( 'active');
}
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + " - " + xhr.statusText);
}
});
}
As you can see I have to toggle the class again using the same code but with direct targeting.
The on off toggles of this type have an onclick inside the actual html calling the function that handles this ajax.
My goal is to have my first set of code the one that targets the element and toggles the class to do all of this, but dynamically to where we don't have to call a function everytime.
Conceptually what I thought is:
$('.on-off').on('click', function(e) {
e.preventDefault();
var $this = $(this);
if (!$this.attr('onclick')) {
$this.find('.slider').toggleClass('active');
} else {
var clickFunction = $this.attr('onclick');
call the clickFunction
if (clickfunction = true) {
$this.find('.slider').toggleClass('active');
}
}
});
What this would do is grab the onclick, but not call it until I specify. And inside the ajax request instead of toggling I would just return true.
This might not be the best method. I am just trying to ecapsulate everything to limit the amount of code as well as make all the dom changes for those elements in one spot for any potential defects.
Here is a link to a basic fiddle of the on/off toggle.
Fiddle
I hope I explained everything in good enough detail.

Two onclick event

I have onclick two times on same button, button for some the second one does not seem to work.
What do i need to do inorder to make both of them work.
<button type="submit" style="display:none;" id="done">Ok</button>
1st event
$(document).ready(function () {
$('#done').click(function () {
});
});
2nd event
$(function () {
$(document).on("click", "#done", Done);
});
function Done() {
$.ajax({
});
}
I believe you need to debug the issue a little bit. The title of the question indicates that javascript (or jQuery) is not handling the click event. This may not be the case.
$(document).ready(function () {
$('#done').click(function () {
console.log('first')
});
});
$(function () {
$(document).on("click", "#done", Done);
});
function Done() {
console.log('second')
}
<button type="submit" style="display:block;" id="done">Ok</button>
This runs fine, see the jsfiddle, the console in my browser logs both first and second messages. So it looks like both events are firing.
You now need to debug your ajax request or your controller. Try getting a simple file (single string within it) and alerting it. Then you can pinpoint your exact problem.
Check the Demo It works
Check the second demo it shows the defualt case ie when it works without error
Depending on the status of the request output is shown here the output is rejected hence enters the fail case
Jquery
$(document).ready(function () {
$('#show').click(function(){
$('#done').show();
});
$('#done').click(function () {
alert('called 1st');
$(this).siblings('.col-lg-11').attr('contenteditable', 'false');
$(this).siblings('.col-lg-11').attr('style', 'border:none;');
$(this).attr('style', 'display:none;');
$(this).siblings('.edit-link').attr('style', 'display:li;');
$(this).siblings('.cancel-link').attr('style', 'display:none;');
});
});
$(function () {
$(document).on("click", "#done", Done);
});
function Done() {
alert('called 2nd');
var s="sa";
var request = $.ajax({
type: "POST",
url: "http://www.google.co.in",
data: { name: "John", location: "Boston" }
}).done(function( ) {
alert( "Data Saved: " );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}

Categories