Getting content: AJAX vs. "Regular" HTTP call - ajax

I like that, these days, we have an option for how we get our web content from the server: we can make an old-style HTTP request (with its own URL in the browser) or we can make an AJAX call and replace parts of the DOM on the fly.
My question is this: how do you decide which method to use when there's an option to use either?
In the "old days" we'd have to redraw the entire page (including the parts that didn't change) if we wanted to show updated content. Now that AJAX has matured we don't need to do that any more; we could, conceivably, render a "page" once and just update the changing parts as needed. But what would be the consequences of doing so? Is there a good rule of thumb for doing a full-page reload vs a partial-page reload via AJAX?

If you want people to be able to bookmark individual pages, use HTTP requests.
If you are changing context, use HTTP requests.
If you are dividing functionality between different pages for better maintainability, use HTTP requests.
If you want to maximize your page views, use HTTP requests.
Lots of good reasons to still use HTTP requests - Stack overflow is a wonderful example of those divisions between AJAX and HTTP requests. Figure out why each function is HTTP or AJAX and I'm sure you will derive lots more reasons when to use each.

My simple rule:
Do everything ajax, especially if this is an application not just pages of content. Unless people are likely to want to link to direct content, like in a blog. Then it is easier to do regular full pages.
Of course there are many blended combinations, it doesn't have to be one or the other completely.

A fair amount of development overhead goes into partial-page reloads with AJAX. You need to create additional javascript handlers for all returned data. If you were to return full HTML blocks, you would still need to specify where the content should go and whether or not it's replacing other content. You would potentially have to re-render header tags to reflect content changes and you would have to implement a history solution to make sure search engines can index each page (using SWFAddress jQuery plugin, for example). If you return JSON encoded data you have an additional processing step.
The trade-off for reduced bandwidth usage by not using a page refresh is offset by an increase in JS code and event bindings which could affect page rendering speed as well as visual effects.
It all really depends on your target audience and the overall feel you are trying to go for on your page. AJAX and preloaders are flashy, and people love flashy things. If you believe the end-user experience will improve by adding partial page loads by all means implement them.

Related

jQuery AJAX Load Method - Delay

I'll admit that I'm pretty new web development (only been coding for about a year) and especially green when it comes to JS / jQuery.
A specific web page I've built loads different data based on hovering over certain categories: country clubs, resorts, hotels, etc. When I built the site on my local machine, the javascript function was super quick. However, on the live site, it has a long delay before the data swap happens.
The URL is: http://preferredparkingsolutions.com/client_list.html
Which links to a javascript function at: http://preferredparkingsolutions.com/scripts/clientHover.js
Which replaces the display div (#client_list) by pulling data from a text file.
Is there a better / faster way of doing this?
Yes, this could be optimised by loading the content in up-front and caching it. Currently you are doing a HTTP request each for each and every hover - even if the user has hovered over that element before, since the AJAX responses aren't being cached. Doing this would be your quickest win.
However, I can't see any case at all for having the content live externally. Is there any reason you're against having the content physically in the page and just using show/hide methods? There's various benefits to this - SEO, for one thing, since Google will find the content.
this is the external page you are loading http://preferredparkingsolutions.com/client_list.inc.html and the content looks little and looks like its a static page then why not just load every thing upfront and then just hide and show div's ? as Utkanos suggested you will aslo have a SEO benifit and also its HTTP request each for each and every hover. if you still want to load it externally lost load it once and cache it and use the cached version to hide and show divs.

one page design

What if use just one html page with blocks inside,
like following
<div id="page1" style="display:block">...</div>
<div id="page2" style="display:none">...</div>
<div id="page3" style="display:none">...</div>
Active block has style="display:block" others "display:none",
when block becomes active "display:block" previous goes "display:none".
AJAX server communication, for instance
$.post("json", { "name": $("#name").val(), "sex": $("#sex").val() },
function(data) { console.log("server responded", data); });
What are disadvantages of this approach?
this is fast and dynamic but this approach lacks of no bookmarking facility, user can't save a particular link because the data is dynamic, also it is not search engine friendly, another disadvantage is history button back and forward will not work.
There are no disadvantages to using pure AJAX. In fact, in a lot of ways, its advantageous.
If you don't plan for it correctly you can have some issues. For example, you're used to having CSS effect 1 page at a time, but with pure AJAX, the CSS will affect every single page.
Also, all things become slightly harder. Linking to another page becomes harder, as you have to use JavaScript.
Lastly, your APP will now REQUIRE JavaScript, so I'd have a decent fallback.
This approach is used in some mobile Web frameworks, such as jQuery Mobile, and is intended to make a Web application feel more native. This is more Web 2.0 than traditional websites or web applications where each page transition involves a trip to the server.
I'm sure you know the advantages already, so let's move on to the disadvantages.
Slightly Greater Initial Latency:
The main disadvantage of this approach is that it will take slightly longer to load the page content due to the fact that you're getting all of the HTML from the server in one single trip. Thus, the initial load time may involve more latency than in a traditional Web 1.0 application. However, with just a few pages, in my experience, the latency is not significant enough for it to be a problem.
Loss of Back Button - More Complexity in Maintaining History:
Another potential disadvantage is that, as a developer, you'll need to approach the development of your site differently. Because you're transitioning pages by hiding one DIV block and unhiding another, you'll lose native back button functionality. This can be mitigated by using the hash in the URL to record the history of page transitions. You'd then need to register an event to watch the hash and reload old content as the user navigates backwards. You'd also need to change the state of JavaScript objects and variables to refect the old state, which may add complexity to your app. There are of course API's and libraries to make this easier to implement and help ensure that you write good, maintainable code.
More Stateful Scope Involves Rethinking Approach and Possible Learning Curve:
Lastly, you'll need to remember that the scope of each page doesn't reset after each transition. While this could actually be an advantage in that your app is more stateful, you'll need to untrain yourself in the way of thinking that each page loaded will cause all of the JavaScript variables and data you've set to be cleared out.
Summary:
My suggestion, if you're going to go this route, is to use a library. Don't reinvent the wheel unless you have a good reason to. Libraries, like jQuery mobile, help ensure that there is good fallback for older browsers, and some even make sure that your site will still load using Web 1.0 techniques for cases where JavaScript is disabled.

What are the cases when AJAX should not be used?

It seems that the sites and applications that use AJAX are growing rapidly. And probably one of the major reasons for using AJAX is to enhance the user experience. My concern is that just because the project CAN use AJAX, doesn't mean that it SHOULD.
It could be that AJAX is exposing more security threats to the site/app for the sake of UX. Maybe you have other reasons for not using AJAX.
When should the use of AJAX be avoided?
Getting Data Already Available Or Data Easily Obtainable
I usually see that on car websites, where there are makes and models. Their usual <select> (without JavaScript) include <optgroup>'s as such:
<select>
<optgroup label="Ford">
<option value="21">Escape</option>
<option value="21">F-150</option>
</optgroup>
<optgroup label="Toyota">
<option value="51">Corolla</option>
<option value="52">Yaris</option>
</optgroup>
</select>
Then usually then proceed to hide that <select> and create 2 new select, one for makes and one for models.
All is fine up to that point. They start messing up here.
They then process to query the server to get a list of makes, and then do another query to get the list of models, when they could of simply parsed the original element try to get their information. Then, everytime you change make, another request is made...
The above is a excellent example of when NOT to use AJAX. Consider this: a request is longer than parsing available data, so they make the user wait. They probably query their database each time, so it has a hit on their server CPU usage. And it incurs more bandwidth. Terrible waste of resources.
What they should have done
They should of have simply parsed the DOM try under the <select> to fetch the relevant information. Each <optgroup> is an item in the makes <select> while each child <option> from the <optgroup> is an item in the models <select>.
Other examples
Using AJAX for simple static DOM modifications (you don't need AJAX to switch from one tab to another in most cases, just include the data in your original request).
Using AJAX to retrieve data on load (why not include it with the original request?)
Using AJAX for an image gallery (why not include the images and manipulate them after the request is done?)
You definitely should avoid AJAX when you are sure that your clients will be using "not javascript enabled" browsers
Actually, AJAX should be used to enhance user interaction. If not it, then Flash or what have you.
Naturally, if there's no possible enhancement, there's no reason to go that way. I tag that as highly unlikely. If you find such a case, blog about it: it'll probably make interesting read.
There are situations, of course, where AJAX is contra-indicated. Basically, when you don't have people using the site. If you expect the site to work with SOFTWARE driving the requests, then you must make sure it works fine without AJAX.
And if you don't expect software to drive the requests, I sure hope you have an alternate API for it, one that can do everything the site can. Otherwise you are just deluding yourself and failing your clients.
If your development time is limited or your team lacks sufficient expertise, then you could make a good case for staying away from AJAX programming.
But otherwise:
[AJAX calls are] no more-or-less safe
than a normal HTTP POST request issued
by a browser as in from a -form-.
The "fix" for this is the same "fix"
for non-AJAX requests - use SSL.
I hear this a lot - just because you can make it pretty with Ajax doesn't mean you should.
I don't think you should necessarily put the UI on the backburner though. It shouldn't be the last thing you think about, particularly in certain cases.
The UI is what the user sees - they don't see any of the complexity behind it, so they'll judge the quality of your site/application based on how easy it is to use and how it makes sense to them.
With that in mind, decide on Ajax based on the user's point of view. Does it make sense that when I click on this button the page slides to the left to reveal a new section? Would it comfort me or confuse me to see the page grayed out and a "Working..." image displayed in front?
When redirecting a user to a new page which the user might want to bookmark - i.e. if clicking on a link causes the content to be updated using AJAX, the user can't bookmark the page.
AJAX should be avoided when the same functionality can be implemented entirely client-side without an additional round-trip to the server.
For example, it may be more efficient to seed the client with a list of zip codes for all US States and scope zip code selection to the appropriate set rather than going to the server for a list of valid zip codes for the given state.
It could be that AJAX is exposing more security threats to the site/app for the sake of UX. Maybe you have other reasons for not using AJAX.
How? What security threats?

load a new page using ajax

I am new to ajax and i wanted to know if we can load a complete new page and not just a part of it using ajax. Please give a small example script for understanding if this is possible. Here i am trying to display only one url to user while i change from one page to another when he clicks on any of the links in the page.
You can of course request for a new page and load it via body.innerHTML = ajax.responseText;
I would strongly recommend against this though for reasons outlined in this post: Why not just using ajax for Page Requests to load the page content?
The whole premise really is that with
AJAX you don't need to reload the
whole page to update a small
percentage of that webpage. This saves
bandwidth and is usually much quicker
than reloading the whole page.
But if you are using AJAX to load the
whole page this is in fact
counterproductive. You have to write
customised routines to deal with the
callback of the AJAX data. Its a whole
lot of extra work for little to no
increase in performance.
General rule for where to use AJAX: If
your updating >50% of your page, just
reload, else use AJAX.
You will not only need to request for the new page, but then also take care of ensuring the old styles on the current page are removed and don't interfere with the new page. Theres all sorts of problems associated with what your trying to do. It's possible, but I recommend not to do it.
edit: actually you might be able to just do document.write(ajax.responseText) which should take care of overwriting everything in the document, including css styles etc. Though still don't recommend it.
When you're finished with processing the AJAX request simply use this JS line:
window.location.replace('<URL of the new page>');
This has exactly the effect of loading the new page via
....
When you make an AJAX request, a request goes off and brings you the contents of the URL that you have requested. Now technically you can do whatever you like with the contents (which could be HTML), you can replace any element within the DOM with it. Be careful however of replacing EVERYTHING on the page, you are more likely just going to want to replace what is within the tags.
If what you want to do is show one URL for multiple pages, AJAX is overkill. Why not just use an IFRAME?
This could be useful if your page was unsure if it was expecting back errors to be inserted onto the page or a "new" submission confirmation page. This can be used when you want to put a validation servlet (or whatever) in front of the submission servlet (or whatever). If the page always hits the validation servlet, you hide the submission servlet which actually performs the data update. In the case where the validation passes, forward to the submission servlet. The user never knows what happened in the background.
When the page gets a response back you could just look at the first portion of the response text and determine if it had a keyword set by the server, which means this is a new page. Remove the keyword from the text, and do document.write(ajax.responseText); as described previously. Otherwise insert the response text into your errorBox div and let the user retry submission.

What are the "best practices" for AJAX with Django (or any web framework)

I am developing an issue tracking application in Django, mostly for a learning exercise but also for my own projects - and I am looking into using some AJAX for "enhanced" usability. For example, allowing users to "star" particular issues, which would add them to their watch list. This is implemented in a lot of sites, and is often AJAX - as the URL that the user is viewing doesn't need to change when they click the star.
Now, I am wondering what kind of response to return from my star_unstar view - that detects whether the request is being made via AJAX or not.
At present, if the request is an AJAX request, it returns just the section of HTML that is needed for the star, so I can replace the HTML in the star's parent DIV, so as the star appears "on" or "off", depending on the user's action.
However, I would much rather return some kind of JSON object, as it just seems more "proper", I think. The problem with this method is that the javascript would have to modify the star image's src attribute, the href on it, and the link title also, which seems a lot of work for such a simple feature. I am also looking into in-line commenting in the future, but I want to get a feel for how things "should" be done before I start coding lots of JS.
What is the general consensus when implementing features such as this, not just with Django, but all frameworks that operate in a similar way?
When I work with Ajax my main concern is usually to limit the amount of data I have to send. Ajax applications of this type should be very responsive (invisible if possible).
In the case of toggling a star, I would create the actual on/off states as CSS classes, StarOn and StarOff. The client will download both the off and on star when they first visit the page, which is acceptable considering that the star is a small image. When you want to change the star appearance in the future, you'll only be editing CSS, and won't have to touch the javascript at all.
As for the Ajax, I'd send back and forth one thing -- a JSON variable true/false that says whether or not the request was successful. As soon as the user clicks on the star, I'd change it to the StarOn state and send out the request. 99% of the time Ajax will return true and the user will not even realize that there was some sort of delay in the web request. In the rare case where you get a false back, you'll have to revert the star to StarOff and display an error message to the user.
I don't think your question relates particularly to Django or Python, as you point out at the end.
There's a lot of personal preference in whether you return a blob of HTML to write into the DOM or some serialized data as JSON. There are some practical factors you might want to take into account though.
Advantages of HTML:
- Easy and fast to write straight into the page.
Advantages of JSON:
- Not coupled to the front-end of your application. If you need that functionality anywhere else in the application, it is there ready to go.
My call on it. It's only a relatively trivial amount of HTML to update, and I'd probably go for returning JSON in this case and giving myself the extra flexibility that might be useful down the road.

Resources