Loader not disappearing after AJAX result is received - javascript

I have page that displays data through AJAX, till the time the result is being fetched I wish to display a loader and as soon as the result is fetched I want that the loader should disappear. Below is part of the code where I am trying to display the loader
var onSubmit = function(e)
{
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$("#walkaway").hide();
$("#submitamt").hide();
$("#xtrabutton").hide();
LodingAnimate();
$.ajax(
{
type: 'post',
url: 'test2.php',
dataType: 'json',
data: {txt: txtbox,hidden: hiddenTxt},
cache: false,
success: function(returndata)
{
$('#first').html(returndata[0]);
$('#second').html(returndata[0]);
$('#third').html(returndata[0]);
},
error: function()
{
console.error('Failed to process ajax !');
}
});
function LodingAnimate()
{
$("#maillist").html('<img src="img/ajax-loader.gif" /> Please Wait Loading...');
}
};
On click of a button the above AJAX is executed, after the click the loader runs but even after I get the reply(in console) the loader keeps on running, but in actual it should have disappeared.

You should hide/remove the loader manually after ajax call completes, add Jquery Complete call back and add the code to remove the loader in it.
Jquery Complete - This call back will execute after success and error call back executed.
$.ajax(
{
type: 'post',
url: 'test2.php',
dataType: 'json',
data: {txt: txtbox,hidden: hiddenTxt},
cache: false,
success: function(returndata)
{
//Success code
},
error: function()
{
//error code
},
complete:function()
{
//This block will execute after success/error executes.
//Make the loader div empty
$("#maillist").empty();
}
});

Related

Prevent Bootstrap Modal from showing using ajax error

I was wondering if there is a way to prevent the Modal from showing up when an ajax call returns an error. I've seen a few posts here already that use
e.stopPropagation();
but I couldn't manage to make that work. My ajax call looks as follow
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function (e) {
//show error message
$('#alertdone').removeClass('hidden');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
//hides the error message
$('#alertdone').addClass('hidden');
}
});
Thanks
I am assuming that you need to hide (don't show) the modal if the AJAX calls fails (since there's a difference between ajax call failing and returning error from server side).
For that you need to remove your data-attribute from HTML and do something like this:
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function (e) {
$('#alertdone').removeClass('hidden');
$("modal_selector").modal('hide');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
$('#alertdone').addClass('hidden');
$("modal_selector").modal('show');
}
});
If you want to hide/ show modal depending on condition use modal()
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function (e) {
//show error message
$('#alertdone').removeClass('hidden');
$("Your_modal_id").modal('hide');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
//hides the error message
$('#alertdone').addClass('hidden');
$("Your_modal_id").modal('show');
}
});

ajax progress loading does not work properly

I am now in javascript, I am trying to display a indictor icon when ajax starts and hide it when it finishes, below is my code:
CSS:
div.ajax-progress {
//some setting and url
}
<body>
<div class="ajax-progress"></div>
</body>
Javascript:
$('#fileToUpload').on('change', function(e) {
var file = e.target.files[0];
var formData = new FormData($('form')[0]);
imageId = cornerstoneWADOImageLoader.fileManager.add(file);
$.ajax({
url: 'loadfile.php',
type: 'POST',
data: formData,
async: false,
dataType: 'json',
timeout : 60000,
beforeSend :function(){
$(".ajax-progress").show();
},
success: function (html) {}
$(".ajax-progress").hide();
//doing something}
});
});
but nothing happens, any idea? appreciated.
Maybe if you put $(".ajax-progress").show(); before the call of ajax $.ajax({}); and them hide it in the succes.
I don't know if that's the same to what you have in your code but you commented out the success closing bracket }
you can also use console.log() or alert() to see what's going on in your code.
Try rewriting your ajax as below:
$.ajax({
url: 'loadfile.php',
type: 'POST',
data: formData,
async: false,
dataType: 'json',
timeout : 60000,
beforeSend :function(){
//do something
},
success: function (html) {
//doing something
}
});
$(document).ajaxStart(function() {
$(".ajax-progress").show();
});
$(document).ajaxStop(function() {
$(".ajax-progress").hide();
});
This will show and hide $(".ajax-progress") in all your ajax requests within the application.

Ajax redirect on error

I'm calling php file through ajax call and if it returns nothing i want to redirect user to another page (It's for error reports, if it doesn't return anything it means that user logged in). Tried to add error section but it doesn't work. Any suggestions will help. Thanks! Btw, I have small jQuery function at the top of the ajax function, why it breaks my whole ajax call?
ajax.js
function loginAjax() {
//$("#email_errors").empty(); //This function doesnt work and kills whole ajax call. Here is loginAjax function call line - <button type = "submit" id = "push_button" onclick = "loginAjax(); return false">PushMe</button>
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
success: function(data) {
$("#login_error").html(data.login_message);
}
});
}
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
success: function(data) {
$("#login_error").html(data.login_message);
},
error: function(){
window.location.replace("http://stackoverflow.com");
}
});
}
To redirect using javascript all you need to do is override the location.href attribute.
function loginAjax() {
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
// the success method is deprecated in favor of done.
done: function(data) {
$("#login_error").html(data.login_message);
},
fail: function(data) {
location.href="path/to/error/page";
}
});
}

Ajax Call waiting for the response of another Ajax Call?

I have two ajax call that cannot be done in one call. When the first ajax call starts the second ajax call can start immediately or whenever the user presses a send button. If the second ajax call starts he has to wait for the response of the first ajax call because he needs data from it.
How can I achieve that the second ajax call sends his request only after the first ajax call's response has been arrived?
Is there another way than setTimeout?
Can I register a listener for ajax call 2 on ajax call 1 somehow?
My code would be:
var xhrUploadComplete = false;
// ajax call 1
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
complete: function(response) {
var returnedResponse = JSON.parse(response.responseText);
xhrUploadComplete = true;
}
});
// ajax call 2
if (xhrUploadComplete) {
$.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false,
complete: function(response) {
...
}
});
}
Edit: The second ajax call cannot be posted in done() or complete() of the first call, because it depends on the users choice to send the final form. The purpose of this two step process is to send an image to the server just after the user had inserted it to an input type=file.
Edit: In know that I cannot the the if(..) because this is an async call. I wrote it to make clear what I need to do. I think I need something like a future in Java.
xhrUploadComplete will be set to true asynchronously (in the future, when the request has finished) so your if-condition (that is evaluated right after the request is started) will never be fulfilled. You cannot simply return (or set) a value from an ajax call. Instead, move the code that waits for the results into the handler that would have set/returned the variable:
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
complete: function(response) {
var returnedResponse = JSON.parse(response.responseText);
$.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false,
complete: function(response) {
…
}
});
}
});
With the Promise pattern you can compose those even more elegantly:
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false
}).then(function(response) {
var returnedResponse = JSON.parse(response.responseText);
return $.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false
});
}).done(function(response) {
// result of the last request
…
}, function(error) {
// either of them failed
});
Maybe you need also need this:
var ajax1 = $.ajax({
url: url, …
}).then(function(response) {
return JSON.parse(response.responseText);
});
$(user).on("decision", function(e) { // whatever :-)
// as soon as ajax1 will be or has already finished
ajax1.then(function(response1) {
// schedule ajax2
return $.ajax({
url: url2, …
})
}).done(function(response) {
// result of the last request
…
}, function(error) {
// either of them failed
});
});

Display loading while retrieving data using Ajax method

I am using ajax, sometimes it takes time to load all the data from my database therefore I need to find a way to display (Loading...) While the data is not yet complete. Below is my sample code, and I am looking for some event while the data is still in process.
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(data){
$('#para').html(data);
}
});
It is very simple..
before you call the ajax start your loading image..& after the success hide the image
for eg :
$.fancybox.showLoading();
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(data){
$.fancybox.hideLoading();
$('#para').html(data);
}
});
here
$.fancybox.showLoading()
is my function in which I have the property of displaying the loader,
This will be internally called whenever an ajax call is made.
$.ajaxStart(function() {
$("img#loading").show();
});
$.ajaxComplete(function() {
$("img#loading").hide();
});
HTML
<img src="../images/loading.gif" alt="wait" id="loading"/>
<div id="loading">LOADING...</div>
var loading = $("#loading");
loading.hide();
function doAjax() {
loading.show();
$.ajax({
url: "/js/beautifier.js",
success: function (data) {
loading.hide();
}
});
}
doAjax();
on jsfiddle

Categories