Fade out on Ajax submit - ajax

I have this ajax submit script. It does submit properly and pops up the thank you message, but it does not fade out in 3.2 seconds. The goal is to have the message "Thank you for updating." pop up for a few seconds each time a user clicks on an update button (#tracking_submit).
$('#tracking_submit').click(function(){
$.ajax({
url: "php/tracking.php",
type:'POST',
data: dataString,
success: function(){
$('#tracking_message').replaceWith("Thank you for updating.");
$('#tracking_message').delay(3000).fadeOut(300);
}
});
return false;
});

I solved this issue this way
$('#tracking_submit').click(function(){
$.ajax({
url: "php/tracking.php",
type:'POST',
data: dataString,
success: function(){
$('#tracking_message').html("Thank you for updating.").fadeIn('slow');
setTimeout(function(){$('#tracking_message').fadeOut('slow');},2000);
}
});
return false;
});

Try using this:
setTimeout(function() { $('#foo').fadeOut(); }, 5000);
.delay() doesn't play well with anything else since the timer keeps ticking and a .dequeue() is executed when it's up...regardless of if you cleared the queue and added a whole new one.
It's better to use setTimeout() directly. setTimeout() is a native javascript function.

Related

AJAX loading image barely visible

I have a simple issue. I am posting data from a form to my DB using an AJAX request. I have coded in a loading GIF using the beforeSend and complete commands in my AJAX request.
<script>
$(function(){
//email the link
$("##emailTicket#get_active_tickets.ticket_id#").submit(function(){
// prevent native form submission here
$.ajax({
type: "POST",
data: $('##emailTicket#get_active_tickets.ticket_id#').serialize(),
url: "actionpages/email_dashboard_ticket.cfm",
beforeSend: function(){
$('.loader').show()
},
complete: function(){
$('.loader').hide();
},
success: function() {
$("##emailTicketResponse#get_active_tickets.ticket_id#").html("");
$("##emailTicketResponse#get_active_tickets.ticket_id#").append( "Ticket successfully sent." );
}
});
return false;
});
});
</script>
Everything seems to be working correctly however the loading GIF only flashes for a split second because the request doesn't take long at all to complete. Sometimes you can't even see it and users are confused if clicking the submit button actually did anything.
Is there a way to delay the 'complete' part of the function so that the animated GIF appears on the screen longer?
complete: function(){
$('.loader').hide();
},
I was able to achieve this by modifying my complete code in my function and adding a delay in milleseconds:
complete: function(){
$('.loader').hide(3000);
},

ajax, if successful refresh after 3 seconds

title says it all, the way the script currently works is if its successful, it brings back a message back from my php code, i want it to also refresh the page after 3 seconds
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "postadvert.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#result').html('<div class="success"><img src="../../images/loading-blue.gif" width="25" /></div>');
},
success: function(data){
$('#result').html(data),
$('#result2').html('<meta http-equiv="refresh" content="3">'); // i added that doesn't working
}
});
});
});
A couple of things. First, you need a semicolon after your first line in the success function. Next, you can use the setTimeout function in javascript where you pass a function and a time to wait in milliseconds. Lastly, you can call the location.reload() to refresh the page.
success: function(data){
$('#result').html(data);
setTimeout(function(){location.reload();},3000);
}
Include the following in your success callback:
window.setTimeout(function() {
document.location.href = document.location.href;
}, 3000);
Assigning to document.location.href automagically causes the browser to load the URL so assigned; assigning its own value back to it therefore causes a refresh. The window.setTimeout() call tells the browser to wait three seconds, then run the function given as its first argument.

Disable ajaxStart() and ajaxStop() for a specific request

I am using .ajaxStart() and .ajaxStop() to show a modal while an ajax request is being made. (between start and stop)
Now I'd like to add a longpoll function that keeps waiting for notifications, similar to the one on the left upper corner of this site.
My problem now lies in disabling this modal only for the longpolling request..
Registering "loading screen" on and off handlers:
$(document).ajaxStart(handleAjaxStart);
$(document).ajaxStop(handleAjaxStop);
My longpoll function:
$.ajax({
timeout: 35000,
url: longPollUrl,
success: function(data){
if(data.queCount) $('#numQueCount').html(data.queCount);
if(data.queAccept) $('#numQueAccept').html(data.queAccept);
},
dataType: 'json',
complete: longpoll
});
I tried:
$().off('ajaxStart');
$().off('ajaxStop');
..and reattaching the handlers after starting the polling, but no joy.
I also tried introducing a global variable into handleAjaxStart() that would return at the first line of the function, but that seems to completely kill the loading screen.
Any ideas how this can be achieved?
I figured it out..
There is an attribute in the options object .ajax() takes called global.
If set to false, it will not trigger the ajaxStart event for the call.
$.ajax({
timeout: 35000,
url: longPollUrl,
success: function(data){
if(data.queCount) $('#numQueCount').html(data.queCount);
if(data.queAccept) $('#numQueAccept').html(data.queAccept);
},
global: false, // this makes sure ajaxStart is not triggered
dataType: 'json',
complete: longpoll
});
After reading all possible solutions, I want to combine answers.
Solution 1: Bind/Unbind
//binding
$(document).bind("ajaxStart.mine", function() {
$('#ajaxProgress').show();
});
$(document).bind("ajaxStop.mine", function() {
$('#ajaxProgress').hide();
});
//Unbinding
$(document).unbind(".mine");
It is a depreciated solution. Before jQuery 1.9, global events of ajax like ajaxStart, ajaxStop, ajaxError etc. can be binded to any element. After jQuery 1.9:
As of jQuery 1.9, all the handlers for the jQuery global Ajax events,
including those added with the .ajaxStart() method, must be attached
to document.
Therefore we cannot bind/unbind these events to custom namespaces.
Solution 2: Set the property global to false
$.ajax({
url: "google.com",
type: "GET",
dataType: "json",
global: false, //This is the key property.
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
This solution works to disable ajaxStart()/ajaxStop() event(s). However, it also makes disable ajaxComplete(), ajaxError(), ajaxSend(), ajaxSuccess(). If you don't use these global events, it seems ok, but when it is needed, you have to come back and change your solution for all pages where you set global: false.
Solution 3: Use global variable
var showLoadingEnabled = true;
$(document).ready(function () {
$('#loading')
.hide() // at first, just hide it
.ajaxStart(function () {
if (showLoadingEnabled) {
$(this).show();
}
})
.ajaxStop(function () {
if (showLoadingEnabled) {
$(this).hide();
}
});
});
function justAnotherFunction() {
window.showLoadingEnabled = false;
$.ajax({
url: 'www.google.com',
type: 'GET',
complete: function (data) {
window.showLoadingEnabled = true;
console.log(data);
}
});
}
Global variables should not be used in javascript files. However, this is the simplest solution, I can find.
I prefered the third solution for my project.

Disable Button while AJAX Request

I'm trying to disable a button after it's clicked. I have tried:
$("#ajaxStart").click(function() {
$("#ajaxStart").attr("disabled", true);
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
},
error: errorhandler,
dataType: 'json'
});
$("#ajaxStart").attr("disabled", false);
});
but the button is not getting disabled. When I remove $("#ajaxStart").attr("disabled", false); the button gets disabled.
While this is not working as expected, I think the code sequence is correct. Any help will be appreciated.
Put $("#ajaxStart").attr("disabled", false); inside the success function:
$("#ajaxStart").click(function() {
$("#ajaxStart").attr("disabled", true);
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
$("#ajaxStart").attr("disabled", false);
},
error: errorhandler,
dataType: 'json'
});
});
This will ensure that disable is set to false after the data has loaded... Currently you disable and enable the button in the same click function, ie at the same time.
In your code, you just disable & enable the button on the same button click,.
You have to enable it inside the completion of AJAX call
something like this
success: function(response){
$("#ajaxStart").attr("disabled", false);
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
},
I have solved this by defining two jquery functions:
var showDisableLayer = function() {
$('<div id="loading" style="position:fixed; z-index: 2147483647; top:0; left:0; background-color: white; opacity:0.0;filter:alpha(opacity=0);"></div>').appendTo(document.body);
$("#loading").height($(document).height());
$("#loading").width($(document).width());
};
var hideDisableLayer = function() {
$("#loading").remove();
};
The first function creates a layer on top of everything. The reason the layer is white and completely opaque, is that otherwise, IE allows you to click through it.
When doing my ajax, i do like this:
$("#ajaxStart").click(function() {
showDisableLayer(); // Show the layer of glass.
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
hideDisableLayer(); // Hides the layer of glass.
},
error: errorhandler,
dataType: 'json'
});
});
I solved this by using global function of ajax
$(document).ajaxStart(function () {
$("#btnSubmit").attr("disabled", true);
});
$(document).ajaxComplete(function () {
$("#btnSubmit").attr("disabled", false);
});
here is documentation link.
The $.ajax() call "will not block" -- that means it will return immediately, and then you enable the button immediately, so the button is not disabled.
You can enable the button when the AJAX is successful, has error, or is otherwise finished, by using complete: http://api.jquery.com/jQuery.ajax/
complete(XMLHttpRequest,
textStatus)
A function to be
called when the request finishes
(after success and error callbacks are
executed). The function gets passed
two arguments: The XMLHttpRequest
object and a string categorizing the
status of the request ("success",
"notmodified", "error", "timeout", or
"parsererror"). This is an Ajax Event.

How to hold a few milliseconds before making a keyup event ajax request in jQuery

I am making a small app using the Google Maps API. You can the type pin in a textbox and an AJAX call will be fired to get the coordinates from my database. I am invoking the action on the keyup event and after 2 characters are in the textbox. The problem is that I want the user to be able to type the whole thing before I start shooting AJAX calls. I have set Asynch to false otherwise the asynchronous call doesn't let me remove the markers from the map and brings in more markers before they are all gone.
$('input[name="location"]').keyup(function(){
if($(this).val().length > 1){
$(this).css('background', '#fff url("/images/indicator.gif") no-repeat center right');
deleteOverlays();
$.ajax({
dataType: "json",
url: "locAjax.php",
data: ({term : this.value}),
async: false,
type: "GET",
success: function(data) {
setMarkers(map, data);
}
});
$(this).css('background', '#fff');
}
});
Can I use some sort of time out or something before the call to give the user time enough to write the whole thing. or at least half of it.
Please let me know.
Thanks a lot.
var timer;
$('input[name="location"]').keyup(function(){
clearTimeout(timer);
timer = setTimeout(function(){
if($(this).val().length > 1){
$(this).css('background', '#fff url("/images/indicator.gif") no-repeat center right');
deleteOverlays();
$.ajax({
dataType: "json",
url: "locAjax.php",
data: ({term : this.value}),
async: false,
type: "GET",
success: function(data) {
setMarkers(map, data);
}
});
$(this).css('background', '#fff');
}
}, 5000 ); // <--- do ajax call after 5 seconds of the last keyup character...
});
Its quite simple, you need to use setTimeout and clearTimeout. For example,
var timerId = null;
$('input[name="location"]').keyup(function(){
if (timerId) {
clearTimeout(timerId);
}
timerId = setTimeout(makeServiceCall, 20); // wait for 20 millisecond.
});
Here makeServiceCall will be the function that will have code outlined by you to make the service call. This function should also reset timerId to null. So whenever key is pressed, we will set the timer to fire service call, if key is pressed before time out occurs then we will reset previous timer and set a fresh one.

Resources