Pages

Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Wednesday, May 18, 2011

Solutions to 5 Common Ajax Problems



The modern web developer who does not consider Ajax when planning or building their websites is potentially missing out on a powerful tool to enhance usability.
There are however, challenges in implementing Ajax functionality on a web page.
In this article we’ll discuss solutions to five of the most common challenges that a developer faces when using Ajax to enhance the content on their website.
Although there is a lot more to discuss and research on all five topics, this post should give beginners and intermediate Ajax developers some solid tips on implementing Ajax functionality in a more user-friendly and accessible manner.

Problem #1: Content Is Not Backwards-Compatible

This problem occurs when a designer has incorporated JavaScript and Ajax enhancements into their website’s architecture without making provisions for browsers that have disabled JavaScript.
Nothing is wrong with planning a website with JavaScript and Ajax; in fact, in today’s market, JavaScript considerations should be integral to the planning process. But you should still ensure that the website is backwards-compatible (or that it degrades gracefully) upon launch.

Solution: Implement Ajax as an Enhancement to an Already-Functioning Website

While Ajax may be integral to your planning of the website’s architecture, ensure that all content is accessible through conventional server-side methods.
Let’s say you have an “Employee Information” page that has a separate link for each employee. Using server-side technology, you could display the content for a particular employee based on a value passed through the query string, like this:
<a href="employees?view=CEO">John Doe - CEO</a>
<a href="employees?view=VP">Frank Smith - Vice President</a>
<a href="employees?view=Accountant">Jim Williams - Accountant</a>
All of the links above point to the same page, the “Employees” page, which changes according to the variable in the query string. Each employee’s information would be loaded from the server, which could be done in a number of ways: via server-side includes; through a database; or even using XML.
Whichever employee link is clicked, the full page would have to load in order for the requested information to be delivered.
So, the content is fully accessible before any Ajax enhancements are layered on top. Then, using JavaScript, the full page refresh could be interrupted and the content loaded instead via Ajax. The clicked link could be identified by an ID or by checking the value of the HREF attribute in the anchor.
Although the content is fully accessible with JavaScript disabled, most users will see the enhanced Ajax-driven version.
The principle of progressive enhancement for Ajax is well known, because it is commonly used for unobtrusive JavaScript techniques and is inherent in CSS, as illustrated by the graphic below:
Ajax as an Enanchement Layer
So, build your website to work without JavaScript, and then add JavaScript as an enhancement, just as you would mark up your content in HTML and then “enhance” it with CSS.

Problem #2: The Browser’s Loading Indicator Isn’t Triggered by Ajax Requests

Almost every browser has a way of visually indicating to the user that content is loading. In current browsers, the indicator appears on the tab that’s loading the content.
The images below show this animated indicator from a few popular browsers.
IE Browser Loading
Internet Explorer’s loading indicator is a solid circle with a gradient that spins while the content loads.

Firefox Browser Loading
Firefox displays a similar icon of small spinning circles in different shades of gray.

Chrome Browser Loading
Google Chrome spins a half-circle.
The problem is that Ajax requests do not trigger this “loading” indicator that is built into browsers.

Solution: Insert a Similar Loading Indicator Near Content That’s Loading

The common solution to this is to incorporate a custom progress indicator into the Ajax request. A number of websites offer free “Ajax loading” graphics.
Preloader.net
Preloaders.net has a number of fancy, customizable animated graphics to choose from.
Implementing this custom loading graphic, or progress indicator, into your website’s Ajax functionality is simply a matter of showing and hiding it at the appropriate times via JavaScript.
Your Ajax code will include lines of code that tell you if the request is in progress or completed. Using JavaScript, you can show the animated graphic while the request is being processed and then hide it when the action has completed.

Problem #3: The User Doesn’t Know That an Ajax Request Has Completed

This is related to the previous problem but is often overlooked, because the developer might assume that the disappearance of the “loading” indicator suffices to inform the user that the content has completely loaded. But in most cases, definitively indicating that content has been updated or refreshed is better.

Solution: Use a Distinct “Request Completed” Message

This can be done similar to how form submissions are confirmed. After a link has been submitted on Digg, the page lets you know very clearly that your submission has been received:
Digg's Form Submitted Indicator
Although this particular indicator does not point out a completed Ajax request, the principle is the same: the “Success” box appears after the page that submits the form has finished loading, and the box is colorful and distinct.
A similar graphic or indicator could be used at the end of an Ajax request to tell users that content has been updated. This would be implemented in addition to, not instead of, the progress indicator proposed for the previous problem.
A similar but subtler way to indicate that an area of content has been updated is the yellow fade technique. This method is familiar to users, unobtrusive and works well with Ajax-loaded content.

Problem #4: Ajax Requests Cannot Access Third-Party Web Services

The XMLHttpRequest object, which is at the root of all Ajax requests, is restricted to making requests on the same domain as the page making the request. But there are instances when you would want to access third-party data via an Ajax request. Many web services make their data accessible via an API.

Solution: Use Your Server as a Proxy

The solution to this problem is to use your server as a proxy between the third-party service and browser. Although the details of this solution are far beyond the scope of this article, we’ll go over the basic principle at work.
Because an Ajax request originates in the client’s browser, it must reference a file at another location but on the same domain as the source of the request.
Your server, however, unlike the client’s browser, is not limited in this way. So, when the page on your server is called, it runs in the background as it normally would but with access to any domain.
This doesn’t present any security risk to the user because the requests to the third-party service are made on your server. So, once the information has been obtained at the server level, the next step in the Ajax call is to send a response back to the client, which in this case would include the data obtained from the third-party web service.
Using Your Server as a Proxy to Access Web Services
If you want more details on this powerful method of combining web-service access with custom Ajax, definitely check out other resources, some of which are listed below.

Further Reading:


Problem #5: Deep Linking is Not Available

This is a trickier issue but may not be required depending on your type of website or application. The problem occurs when content is loaded via Ajax and then the “state” of the website is changed without the URL that points to the page being affected.
If the user returns to the page via a bookmark or shares the link with a friend, the updated content will not be automatically displayed. The website would instead revert to its original state. Flash websites used to have the same problem: they did not allow users to link to anything but the initial screen.

Solution: Use Internal Page Anchors

To ensure that a particular “state” on an Ajax-driven web page is linkable and bookmarkable, you can use internal page links, which modify the URL but don’t refresh the page or affect its vertical position.
This simple code demonstrates how this is done:
var currentAnchor = document.location;
currentAnchor = String(currentAnchor);
currentAnchor = currentAnchor.split("#");

if (currentAnchor.length > 1) {
 currentAnchor = currentAnchor[1];
} else {
 currentAnchor = currentAnchor[0];
}

switch(currentAnchor) {
 case "section1":
 // load content for section 1
 break;

 case "section2":
 // load content for section 2
 break;

 case "section3":
 // load content for section 3
 break;

 default:
 // load content for section 1
 break;
}
The above is not a functioning piece of code but rather a theoretical example to demonstrate the main steps involved.
The first two lines of code put the current page location (URL) in a variable. Then the location is converted to a string so that we can manipulate it.
Next, we “split” the string into two parts via the anchor symbol (#) and subsequently check to see if the array that is created from the split is greater than one item. Greater than one item means that the URL has an anchor.
If the URL has only one part, that means no anchor is present. The subsequent “switch” statement loads content according to the value of the anchor. The switch statement has a “default” option in case no anchor is present, which would be the same as loading the page in its original state.
Furthermore, we would apply code to deal with links that point directly to specific content through internal anchors. A link that points to “content2″ would load the content in “content2,” and the string “#content2″ would be appended to the current URL.
This would change the URL by adding an internal anchor, without changing the view of the page but preserving an identifier that indicates the desired state of the page.
This explanation is only theory. The concept works, and it works very well. But I haven’t explained all of the possibilities, drawbacks and other subtleties of building a website or page in this manner.
Follow the links below for a more comprehensive discussion of the topic, or experiment with it yourself. Also, note that this can be tested using content that changes with JavaScript alone, and doesn’t need to utilize Ajax.

Further Reading:


This post was written exclusively for Webdesigner Depot by Louis Lazaris, a freelance writer and web developer. Louis runs Impressive Webs, where he posts articles and tutorials on web design. You can follow Louis on Twitter or get in touch with him through his website.
Do you know of any solutions to these or other Ajax challenges? Please share your comments below…
read more...

How Ajax Works


In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the “Submit” button to send/get the information, wait for the server to respond, and then a new page will load with the results.
Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly. With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object.
With an HTTP request, a web page can make a request to, and get a response from a web server, without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.
This picture is a simplified introduction about how Ajax works:

The user sends a request that executes an action and the action’s response is showed into a layer, identify by an ID, without reload the full page. For example a layer with this id:
<div id=”ajaxResponse”></div>
In the next steps we will see how to create an XMLHttpRequest and receive response from the server.

1. Create XMLhttpRequest

Different browsers use different methods to create the XMLHttpRequest object. Internet Explorer uses an ActiveXObject, while other browsers use the built-in JavaScript object called XMLHttpRequest.
To create this object, and deal with different browsers, we are going to use a “try and catch” statement.
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e)
{
alert(“Your browser does not support AJAX!”);
return false;
}
}
}

2. Sending request to the server

To send off a request to the server, we use the open() method and the send() method.
The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously. The send() method sends the request off to the server.
xmlHttp.open(“GET”,”time.asp”,true);
xmlHttp.send(null);

3. Writing server side script

The responseText will store the data returned from the server. Here we want to send back the current time. The code in “time.asp” looks like this:
<%
response.expires=-1
response.write(time)
%>

4. Consuming the response

Now we need to consume the response received and display it to the user.
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
xmlHttp.open(“GET”,”time.asp”,true);
xmlHttp.send(null);
}

5. Complete the code

Now we must decide when the AJAX function should be executed. We will let the function run “behind the scenes” when the user types something in the username text field. The complete code looks like this:
<html>
<body>

<script type=”text/javascript”>
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e)
{
alert(“Your browser does not support AJAX!”);
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
xmlHttp.open(“GET”,”time.asp”,true);
xmlHttp.send(null);
}
</script>
<form name=”myForm”>
Name: <input type=”text”
onkeyup=”ajaxFunction();” name=”username” />
Time: <input type=”text” name=”time” />
</form>
</body>
</html>
read more...