I have two jsp pages and one servlet. When user clicks submit button then processing is done in servlet and then result goes to another jsp page so that user sees his result. But I want to show a loading gif so that that gif will run till user gets his result and if in the mid time user stops that browser from loading then automatically that gif will also stop, how to do it?? In javascript or other only user will see that gif picture but when user will stop browser's processing still that gif is running which should not happen. How can i resolve this??
index.jsp---------------goes to a servlet------------result.jsp
Since all of this is going to happen in the user's browser, the solution cannot be in Java, it will have to be JavaScript, reacting to the onabort event.
As for stopping a GIF animation, that's not really possible (except perhaps through nasty hacks). I suggest using JavaScript (e.g. jQuery builtins or plugins) to do the animation as well.
Update: On second thought, why do you think you need to do anything at all? If the browser aborths the loading, it's their own fault, and the browser already has a loading animation that does exactly what you want. Why duplicate that?
That's nothing Java specific since everything will happen in the browser. You might need some JavaScript to open up that popup before the request is issued and register an event handler that closes the popup on window.onabort.
Try this
function doWork() {
//start loading gif
$.ajax({
'type': 'POST',
'cache': false,
'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
'url': #your_servlet_url#,
'data': $('form#' + #your_form_id#).serialize(),
success: function (data) {//data can be json or plain HTML depending on your scenario
// stop the loading gif
//redirect to result.jsp if you need to redirect user to completely new page with 'data' received
// or just send the result.jsp with processed data from the servlet and load the content 'data'
// received above in some div on index.jsp
},
error: function (xhr, status, err) {
//request cancelled by user or due to any other reason such timeout
if (xhr.status == 0) {
//stop the loading gif
}
// you can handle other errors(401,403 etc) too by examining xhr, status and err objects
}
});
}
Two things I can think of:
on submit simply show the gif. All browsers I have checked will not change the current page until the result from the second one is received.
use ajax (jQuery) to show the results. Then you can use an ajax activity indicator
The jQuery JavaScript library probably can provide some nice in progress effect.
For the future: HTML5 has a progressbar or such.
Use of Ajax might make sence (callback when loaded say inside DIV).
A very crude solution would be to use ajax for your form submit. You can display a loading gif on submit and as soon as you receive a response update the page and remove the gif.
Jquery ajax method would be able to handle abort by user, which would enable you to write logic to remove the gif for instance(or any other processing on page in case of abort)
Other possibility is if you use frameworks like struts(2.0). This gives a wait and execute interceptor especially for this kind of purpose(display an intermediate page while request is processed)
Related
I am building a application with many form submissions and using ajax to send data to server (node js). I have a table to be updated on a button click , and on click I need to load a spinner and call the ajax post request to server. On server it takes some time to update and send back result to ajax success. So on ajax success I hide the load spinner and update the data to table. Everything works fine problem is meanwhile when ajax req is called and server side is executing query the user may reloads the page, when page reloads ajax call is cleared so i cannot hide the load spin and update success data to html. What is the possible solution to avoid this
$.ajax({
url: url,
type: 'POST',
processData: false,
contentType: false,
data: formdata,
success: function (data) {
if (data.status == 'Success') {
toastr.success(data.msg);
// code to hide load spin
// update result data to html
}
})
You can do three things listed below in the order of complexity:
1. Put warnings on the page for users not to press reload or back buttons. This approach is often adopted on payment gateways when credit card details are verified server side. You can show a modal dialog box with the warning and spinner graphic.
2. Use session variables on server side to detect interruptions to ajax calls. For example you can have a variable called ajax_status (values none, incomplete and complete). You can set this variable at the start and successful completion of an ajax call. On page load, if you find the variable set to incomplete, show an error message, saying ‘something went wrong, have you pressed the reload button?’
3. Extend the 2nd approach to save ajax call parameters and reinitiate the request on page reload (show a warning saying data refresh was interrupted and reinforce message re not reloading).
You can avoid a page refresh(re-load) while all of your code is being executed by changing your html form action -
<form id="myForm" action="javascript:void(0)"></form>
This will also maintain HTML standards without fancy code to manipulate element functions.
I am a novice writing a website using jquery and jquery mobile. This loads a set of questions in the form of a JSON file, using jquery ajax, and then users work through questions. On first opening, the page successfully opens 2 JSON files using code that looks like this:
function loadJSON (keytoload) {
$.ajax({
url: keytoload,
dataType: "json",
async: false,
success: function (keyloaded) {
dataset=keyloaded;
},
error: function (request,error) {
alert('Error has occurred please try again!');
}
});
}
I find that async has to be set to false for this to work. If async is true, the page is displayed without the data from the JSON file.
After the user works through a series of steps, a new JSON file is loaded to replace the first and this usually works fine. However, reloading the page is erratic. It works fine in Firefox/Chrome on Windows, but throws an error if a page refresh is done when loading on Android Chrome. So I assume there is a problem in my code somewhere.
Is there a better way I could do this?
Your problem here is cause by the fact that you don't use ajax correctly. You don't know how long is going to take until the result comes back from the server.
A correct architecture here will be:
display an loading div before starting ajax.
On success add the questions in the page.
On next display the loading again.
On success render the new content.
Just setting an variable on success is wrong; on success you render the content based on the values from backend. Also using an ajax in a synchronous way is not recommended, since it can block the script.
I am trying to load the HTML content of a webpage outside of my domain, which I can do just fine using functionality provided by this jQuery plugin: http://www.ajax-cross-origin.com/. However, when I print out the HTML there are pieces missing, which I assume is because the ajax request gets the HTML before the page is fully loaded. When I say "pieces missing," I mean that some tags that should have innerHTML in fact have none. Here's my code:
$.ajax({
crossOrigin: true,
url: "http://siriusxm.com/bpm",
success: function(data) {
console.log(data);
},
timeout: 5000
});
The crossOrigin attribute is from the plugin I mentioned. I get the same behavior with and without the timeout (and strangely, it doesn't seem as though the timeout is doing anything at all--when I check the console, it logs data pretty much immediately).
Is there a way to wait until the page is fully loaded before getting the content? For what it's worth, this is all part of a chrome extension I'm developing, so if there's anything else code-wise you might need just ask.
Thanks!
So according to your comments, the information you're looking for is just the Now Playing artist and Song, which you won't be able to get by loading just the source of the main page.
To find the data you're looking for just open up your Chrome DevTools, go to the network tab, and Refresh to see all requests on the page.
It looks like this is the request you want, you just need to update the timestamp every minute:
http://www.siriusxm.com/metadata/pdt/en-us/json/channels/thebeat/timestamp/08-12-03:48:00
Just parse that json and grab what you need. Of course they can always change the location or format of the file, but for right now that's what it is.
If the console log is showing all of the data you're looking for then the ajax call should be fine.
Any code in the success callback will be ran after the ajax call, so just use JQuery in the success callback function to insert data into the html. All I see there now is the console.log(data) unless you've removed some code.
The timeout just gives the ajax call a set amount of time to complete before it "times out", in other words it tells it to stop waiting after the set amount of time.
I want to know if it is possible or if there are any plugins that can be used with Ajax in that while Data is being fetched in the background, it shows the percentage and it completes 100% after the data has finished loading.
Is that possible using jquery and also are there any plugins for that ?
Do you have one request or several? If you have only one request I don't think that javascript can solve this problem because your code is notified only when request is completed and response is received. So if you want to show percentage you should perform several requests. In that case you know how many chunks do you received and how many are remained.
However if you can show only progress bar without percentage you may do something like that:
function load(){
showGifProgressBar();
$.post(url, function(data){
hideGifProgressBar();
});
}
where showGifProgressBar will show any gif image(Loading gif examples)
It is not possible in JavaScript at all to get progress of ajax call, there is no native functionality in the AJAX. There is not any plugin to do so.
You can show loading image when you start ajax call and hide the image when you will get response from server or your success function is called. The example code as follows:
showLoadingBar();
$.ajax({
url:'/your/url',
success:function(response){
hideLoadingBar();
}
})
I've got a bunch of javascript working on this page so that users can fill the form which includes a file upload field. They can add these forms to a "queue" which is just a series of iframes with the forms data moved into it. With the click of a button it will go through each form and submit them one at a time. When each form is submitted I load a gif to show that there is action. When the processing page is finished it will spit some jquery back at the iframe and give a success or error message. This works great so long as the files are not too large. It seems that the larger files (near 1GB) results in a condition where the jquery from the processing page never shows up in the iframe. This is disastrous because the submitting page will not continue to submit forms unless it gets some sort of response. Also the user is left with a spinning image that never goes away, and are unsure if even one large file has actually uploaded. I've tried setting the max_execution_time and max_input_time for an hour, but this doesn't help at all. Currently using a jquery/javascript to loop through each form and submit it. Can anyone tell me why this is happening and/or how to resolve this issue?
You can set the timeout with jQuery ajax to be longer - From the documentation.
timeoutNumber
Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.