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.
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'm attempting to AJAX in an MVC View to an empty tag using the standard jQuery AJAX call:-
function AjaxLoadPanel(url, id) {
var a = 1;
$.ajax({
url: url,
cache: true,
type: "GET",
success: function (data) {
if (data == "PageNotFound") {
window.location = "page-not-found";
}
else {
$(id).html(data)
}
},
error: function (response) {
$(id).html("");
}
});
}
The MVC controller simply returns the View with an MVC form within, and a HTTP Post beyond that to accept form data. When I put the pages with the div tag and the DLL and views on the server however, there is significant lag before the div tag is populated with the view return from the AJAX call. When I say significant lag, I mean 30 to 60 seconds after the page has loaded. The AJAX call does eventually finish, but such a problem renders the page useless to the unsuspecting user.
Stuff I've checked:-
All scripts are local to the site, no calls to external JS files.
All CSS are local to the site, no external calls.
The view and DLL's are definitely in the correct place
There are no scripts in the head tag.
The view does eventually get AJAX'd into the correct panel.
The wait time comes from calling the view specifically. Navigating to the URL of the view results in a 30 - 60 second wait before the view is returned.
How can I speed up the retrieval of the view? I need it to be within 1 second of page load if at all possible? Also, on localhost this feature works at lightning speed, loading in around 0.2 / 0.3 seconds.
Could it be the server being slow?
Thanks!
Mike.
Check your browser's network panel how long does the AJAX request takes to load.
I am quite sure it is problem with the backend/server. Are you 100% sure that the server backend code is same as your localhost backend code? Also do you use any database to retrieve the data. Could be also database issue.
We found the issue eventually. A datbase connection string login was wrong and the 30 second wait was always 30 seconds because of the length to try and connect to the database for, before causing an exception. At 30 seconds those views that don't directly rely on a database connection are still retrieved, hence the 30 second wait every time.
Thanks for your help!
Mike.
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 have a auto-complete form that fetches result from server, but on slow connection it becomes erratic as data loading takes time. Is there anyway we can prefetch data from ajax source
Just to answer your question, prefetch is possible using synchronous AJAX. Using jQuery, it will be (check syntax since I am on phone).
$.ajax({
url: "",
async: false,
success: function(resp)
{}
});
This will make sure that your data is loaded before you publish it. But as Sinethera said, this defeats entire purpose of AJAX. If you can pre-fetch the content, that means you know the expected content. Then why not put it as a static list?
Prefetch? Isn't that called "not being ajax"? Just load the data with the page and use it as a static data source.
Optionally get the data when they "focus" the field. That would be the only real compromise between getting the data on page-load and doing a legitimate dynamic source.
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)