Loading gif image is not showing in IE and chrome - javascript

I am using JQuery ajax call for sending synchronized call to server and want to display a loading image for that time.
But loading image is visible in Firefox but not in IE and chrome. When i debug, i found that in IE, when we call java script, it stop showing changes in browser as it halts DOM and when the call is completed, it then shows all the changes. Since i shows the loading image on ajax call and remove it after completing the call, the IE doe not display any image.
But when i use alert box,it shows the loading image in IE as it stop the thread until we response to it.
Is there any method to stop java script execution for a millisecond such that IE execution halts and loading image is shown.
I already tried ajaxSend, ajaxComplete, ajaxStart, ajaxStop of JQuery and timer event of java script, but does not get any solution.
Any help is precious, thanks in advance.

In the context of XHR, synchronously means just that the browser freezes until the request is complete. If what you want is to make sure only one request is running at a given time, then use your own flag to indicate that a request is in progress.
By definition, the synchronous flag of a request means that any other activity must stop. I'm surprised that it even works in Firefox, last time I tried that it didn't work, but that was a long time ago. So forget about it, there's no way to make it work in all browsers. Even if you delay the request using a setTimeout, at best you'll get a frozen browser with a non-animated gif. And users don't like when you freeze their browser, especially if the request might take more than a fraction of a second.
Don't ever depend on the browser for security or correct functionality related features. If your application might get broken if a client does two requests in parallel, then you have a bug on the server side. There's nothing that prevents a malicious user from making parallel requests using other tools than the normal UI.

You problem is probably the 'synchronized' part in your opening post.
Open the connection asynchronously. That stops the browser from locking up, and it will work as you expect. (set async = true on your XmlHttpRequest / activex object)

try to shows the loading image at the start of your ajax jquery call and hide it on success event
or
you can use set time out also

I also faced similar problem while working with ajax like i applied some styles to UI during ajax call but these are not applied to UI and same as you told that if we put some alert it will work as expected until OK is not clicked for alert
I can't guess why it happening but you can use JQuery to show or Hide that Loading.... div
Hope it will work....

I had a similar problem and then I sorted it out by using the Update Panel in ASP.NET. If you are using PHP or any other technology then you have to use ajax call. If you do synchronized call then the Loading image will not be shown.

I have had similar situation to deal with, if you have to make the synchronous call, browser will suspend the DOM manipulation. So unless absolutely necessary, keep with the async calls.
There is a workaround for manipulating the DOM and show an element before starting the ajax call. Use jQuery animate(), and make the ajax call in the callback for animation complete. Following code works for me:
//show the loading animation div
$('#loading').show();
//call dummy animate on element, call ajax on finish handler
$('#loading').animate({
opacity: 1
}, 500, function() {
//call ajax here
var dataString = getDataString() + p + '&al=1';
$.ajax(
{
type: 'GET',
async: false,
url: 'uldateList.php',
data: dataString,
dataType: 'json',
success: function(result){
//Do something with result
...
//hide loading animation
$('#loading').hide();
}
});
});

You can try to execute the ajax synchronous call in the image load callback.
Something like:
var img = new Image();
img.src = "loading.gif";
img.onload = function() {
/* ajax synch call */
}
Then append img to DOM.

Hi try to modify ajax call like this its works for me
xmlHttp.open('POST', url, true);
xmlHttp.onreadystatechange = myHandlerFunction;
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.setRequestHeader("Accept-Charset", "charset=UTF-8");
xmlHttp.send(query);

I used Sergiu Dumitriu's information as base. I set my async to true and added
beforeSend: function() {
$('#Waiting').jqmShow();
},
complete: function() {
$('#Waiting').jqmHide();
}
And it worked for me. Basically i created my own async:false attribute.

In your $.ajax call you need to add async: true. Following code works for me:
$.ajax({
url: 'ajax_url',
data: 'sending_data',
type: 'POST',
cache : false,
async: true,
beforeSend: function() {
$('#id_of_element_where_loading_needed').html('html_of_loading_gif');
},
success: function(data) {
$('#id_of_element_where_result_will_be_shown').html(data.body);
}
});

Related

running jquery.ajax causes to slow down in navigating to other page

I have jquery.ajax that always requesting data to the server.My problem is that when I
click some navigation menu I can't navigate it is very too slow.I tried to comment the method inside the success,it works fine I can navigate very fast because there is no request running...Any Idea how to make this work to have request running at the same time and I can navigate to other page.?.
More input greatly appreciated.
Thank you in advance.
$(function(){
getUpdates();
});
function getUpdates(){
type: "GET",
dataType:'json',
url: "updates.php",
error: function () {
setTimeout(getUpdates, 5000);
},
success: function(data){
//do something with the data
...
...
...
getUpdates(); //call again the function
}
});
}
It's not a good idea to start a new request as soon as the previous request finishes. There is no (good) solution for your problem - the best idea is to restructure your code. Since you're constantly pooling the server for new information, you might want to look into Comet or Socket.IO to implement some sort of push mechanism from the server.
That said, for a simple speedup, the best thing you can do is add a timeout in the success function, the same way you did with the error function.

Efficient way of passing data and calling background script in PHP

I have a page where I show 5 questions to a user and when he clicks on Next 5 link I am sending the score of current page onbeforeunload() to the script updateScore() asynchronously using jQuery AJAX and when the call is successful the next 5 questions are displayed.
window.onbeforeunload=function()
{
$.ajax({
type: "POST",
url: "updateScore.php",
data: "pageScore="+score,
cache: false,
timeout:5000,
async:false
});
}
But the problem is that on slow connections,it might hang the browser for a while until AJAX call returns successfully.When I tried async:true(default) the next page is loaded first without making call to updateScore.php.It might be due to the fact that connection is fast in localhost hence giving no time for the AJAX call to complete.This was the reason I used async:false.Will it happen (making no AJAX call) if I use async:true in practical case as well?If yes, is there a way to come around this problem?
I advice you to change your code a bit.
Make ajax request on "click" event, and redirect user inside ajax callback function.
Like this:
$('#mybutton').on('click', function()
{
$('#pleasewait').show();
$ajax({
type: "POST",
url: "updateScore.php",
data: "pageScore="+score,
success: function() { document.location="nextpage.php" }
});
}

Page waits for AJAX before changing location

This question might seem a bit odd, the problem arised when the page went through webtests.
The page uses an AJAX call (async set to true) to gather some data. For some reason it won't swap pages before the AJAX call has returned - consider the following code:
console.log("firing ajax call");
$.ajax({
type: "POST",
url: "requestedService",
data: mode : "requestedMethod",
cache: false,
dataType: "json",
success: function() { console.log("ajax response received") },
error: null,
complete: null,
});
console.log("changing window location");
window.location = "http://www.google.com"
The location only changes after AJAX returns the response. I have tested the call, it is in fact asynchronous, the page isn't blocked. It should just load the new page even if the AJAX call hasn't completed, but doesn't. I can see the page is trying to load, but it only happens once I get the response. Any ideas?
The console output is:
firing ajax call
changing window location
ajax response received
This seems to work fine for me. The location is changed before the code in the async handler executes. Maybe you should post some real code and not a simplified version, so that we can help better.
Here is a demonstration that works as you expect: http://jsfiddle.net/BSg9P/
$(document).ready(function() {
var result;
$("#btn").on('click', function(sender, args) {
setInterval(function() {
result = "some result";
console.log("Just returned a result");
}, 5000);
window.location = "http://www.google.com";
});
});
And here is a screenshot of the result: http://screencast.com/t/VbxMCxxyIbB
I have clicked the button 2 times, and you can see in the JS console that the message about the location change is printed before the result each time. (The error is related to CORS, if it was the same domain, it would navigate).
Bit late but maybe someone else will have the same issue.
This answer by #todd-menier might help: https://stackoverflow.com/questions/941889#answer-970843
So the issue might be server-side. For eg, if you're using PHP sessions by default the user's session will be locked while the server is processing the ajax request, so the next request to the new page won't be able to be processed by the server until the ajax has completed and released the lock. You can release the lock early if your ajax processing code doesn't need it so the next page load can happen simultaneously.

How do I call a JS callback when a file upload completes?

I'm creating frontend upload for an app with appengine backend.
What I want to make is a file upload solution, and I dont want to be using plupload or those kinds of ready-made solutions.
I basically submitted the images to an iframe and then put a cover while it is uploading. Then after it finishes I performed an ajax call to get the image ids for the next view to be rendered. However, the render is always called before the upload is completed, thus I'm not getting any image ids from the backend. can anyonehelp?
here's my code for the upload
perform_input3:(event)=>
event.preventDefault()
$('#product-input-3').hide()
$('#product-input-3').submit()
$('#upload-cover').show()
item_id = $('#item3_id').val()
app.views.imageselect.render(item_id)
the app.views.imageselect.render(item_id) is below:
render:(data)=>
#item_id = data
item_id = #item_id
$.ajax(
url: '/get_image_list/'
type: 'GET'
dataType: 'json'
data: {item_id: item_id}
success:(data) =>
#payload = data
$(#el).append imageSelectTemplate(#payload)
return #
)
I dont want to be using setTimeout function since it will not be flexible depending on the connection speed. Any help will be appreciated :)
Essentially, your question boils down to this: You want to wait to make your Ajax call to the server until the data you're requesting is available. Getting notifications from the server is tricky (depending on how your backend is implemented), so the best solution to your problem is probably to just make the Ajax call periodically (say, once per second) until you get a successful response from the server.
Here's some code that should do that:
do ajaxCall = =>
$.ajax
url: '/get_image_list/'
type: 'GET'
dataType: 'json'
data: {item_id: item_id}
success: (data) =>
#payload = data
$(#el).append imageSelectTemplate(#payload)
error: ->
setTimeout ajaxCall, 1000
If you are only targeting modern browsers, then XHR2's FormData can enable a very simple and elegant approach.
The concept is:
add file(s) binary data to a FormData object
make a $.ajax() call with the FormData object as the AJAX call's "data" parameter
when upload is done, the $.ajax()'s success() or complete() callbacks will be triggered
This approach works with the latest Firefox, Chrome, Safari - http://caniuse.com/xhr2.
See this post for details: Sending multipart/formdata with jQuery.ajax
What you're missing is some sort of callback from the $('#product-input-3').submit() call. I think the following would work (pardon my bad CoffeeScript):
perform_input3:(event)=>
event.preventDefault()
item_id = $('#item3_id').val()
$('#product-input-3').hide()
$('#upload-cover').show()
$('#product-input-3').submit()
$('#target-iframe').ready ->
app.views.imageselect.render(item_id)
This is predicated on the idea that calling 'submit' immediately puts the target iframe into non-ready state, which seems reasonable, but I'd test it. Once it finishes loading The other option I've seen around is to have the page the iframe loads call back into its parent (top-level) window. In JS, something like:
parent.imageUploaded()
Or, if you want to use bound events:
parent.$(parent.document).trigger('upload-complete')
Where, of course, you've set up an upload-complete event on the top-level document object.

jQuery ajax call in onunload handler firing AFTER getting the page on a manual refresh. How do I guarantee onunload happens first?

I have a situation where on page unload I am firing a request to delete the draft of a user's work. This works fine until a user chooses to refresh the page, whereupon inspecting Chrome's network tab shows that Chrome is loading the new page before the ajax request is actually fired. The result is a new draft is created by the page load, and then deleted right away by the ajax call. Here is basically what I'm doing:
window.onbeforeunload = function(){
if (pageUpdated){
return 'Are you sure you want to abandon this draft?';
}
}
window.onunload = function(){
$.ajax({
async: false,
type: 'DELETE',
url: '/some/url/'
});
}
Is there a way to force the onunload handler to complete before the request for the new page is sent?
Browsers Tested: (Chrome 9, FF 3.6) on Ubuntu 10.04 Lucid
In onbeforeunload or $.unload() set up your AJAX object with async = false. This will make sure the ajax call completes before the page is unloaded.
I know this question is a few months old, but I wanted to add this info in case it helps anyone searching for a similar issue with AJAX!
Making the XHR request synchronous should delay the loading of the new page until after the request is complete. I don't know how jQuery runs its synchronous XHR requests under the hood, but here's how you can do it using plain JavaScript:
var request = new XMLHttpRequest();
// or new ActiveXObject("Microsoft.XMLHTTP") for some versions of IE
request.open("GET", "/some/url", false);
request.send(null);
var result = request.responseText;
alert(result);
Putting that in your unload handler should make the browser wait until "/some/url" is loaded before it moves on to the next page.
I'm here to confirm #Silkster answer. I can fire an AJAX request after set an option async = false
Here is the example code.
$(window).unload( function () {
$.ajaxSetup ({
async: false
});
$.get("target.php");
});
You can try using window.onbeforeunload instead, though I'm not sure if it's implemented in all browsers.

Categories