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

Very Dynamic Web Interfaces

One of the classic drawbacks to building a web application interface is that once a page has been downloaded to the client, the connection to the server is severed. Any attempt at a dynamic interface involves a full roundtrip of the whole page back to the server for a rebuild--a process which tends to make your web app feel inelegant and unresponsive. In this article, I'll be exploring how this problem can be tackled with the use of JavaScript and the XMLHttpRequest object.

I'm sure you're familiar with the traditional interface model for a web application. The user requests a page from the server, which is built and delivered to the browser. This page includes an HTML form element for capturing data from the user. Once the user posts their input back to the server, the next page can be built and served based on the input, and so the process continues. This is largely dictated by the nature of HTTP and differs from the traditional desktop application model of an interface which is inherently connected to the application layer.

Take the simple example of filling out a serial number box to register a desktop app on a platform like Microsoft Windows. According to convention, once you've finished typing that tiresome string of alphanumeric into the little boxes, a big green 'tick' icon appears to indicate you've entered a valid code. This happens instantly as a result of the interface being sewn to the application; as soon as you finish typing the number, the application is able to check its validity and respond.

Contrast this to the standard behavior of the same task represented through a web interface. Sure, all the boxes for keying in the serial number will look identical, but on completing input, the user would need to submit the page back to the server for the input to be validated. A new page would then load with a message to indicate success or failure, and on failure, the user would need to go back and try again ad infinitum.

So whilst it's not terribly common that a user would be asked to enter a serial number into a web application, there are countless other examples of user actions that can benefit from very fast reactions from the interface, and when the business logic is all the way back at the server, this can be difficult to achieve in a traditional web app.
Enter JavaScript

Through the use of JavaScript, a reasonable amount of logic can be added to an HTML page in order to give timely feedback to user interactions. This has some major drawbacks, however. The first problem is that, as the JavaScript has been delivered to the browser along with the page, that logic has been opened up to interrogation. This might be fine for checking the format of an email address but would be no good for something like our serial number example, as the exposure of the method of verifying that input would compromise the integrity of the serial number mechanism.

The second problem with including any serious logic within the page is that the interface layer is simply not the place for serious logic. This belongs in the application layer, which is way back at the server. The problem is compounded by the fact that JavaScript cannot usually be relied upon to be available at the client. Whilst the majority of users are able and willing to run JavaScript in their browser, a considerable number prefer not to, or browse with a device where JavaScript is either unavailable or makes no sense. Therefore, any logic operations performed with JavaScript at the client must be verified at the server in case the operation never occurred.
The XMLHttpRequest Object

A solution to these problem presents itself in the form of the XMLHttpRequest object. This object, first implemented by Microsoft as an ActiveX object but now also available as a native object within both Mozilla and Apple's Safari browser, enables JavaScript to make HTTP requests to a remote server without the need to reload the page. In essence, HTTP requests can be made and responses received, completely in the background and without the user experiencing any visual interruptions.

This is a tremendous boon, as it takes the developer a long way towards achieving the goals of both a responsive user interface and keeping all the important logic in the application layer. By using JavaScript to ferry input back to the server in real time, the logic can be performed on the server and the response returned for near-instant feedback.
The Basics

Due to its history, and not yet being embodied in any public standard (although something similar is in the works for the proposed W3C DOM Level 3 Load and Save spec), there are two distinct methods for instantiating an XMLHttpRequest object. For Internet Explorer, an ActiveX object is used:

var req = new ActiveXObject("Microsoft.XMLHTTP");

For Mozilla and Safari, it's just a native object:

var req = new XMLHttpRequest();

Clearly, as a result of this inconsistency, it's necessary to fork your code based on support for the appropriate object. Whilst there are a number of methods for doing this (including inelegant browser hacks and conditional comment mechanisms), I believe it's best to simply test for support of either object. A good example of this can be found in Apple's developer documentation on the subject. Let's take their example:

var req;

function loadXMLDoc(url)
{
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send(null);
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send();
}
}
}

A particularly important property to note is the onreadystatechange property. Note how it is assigned to a function processReqChange. This property is an event handler which is triggered whenever the state of the request changes. The states run from zero (uninitialized) through to four (complete). This is important because our script isn't going to wait for the response before continuing. The HTTP shenanigans are initiated, but then they carry on out of process whilst the rest of the script runs. Due to this, it's not as simple as having loadXMLDoc return the result of the request at the end of the function, because we don't know if we'll have a response by then or not. By having the function processReqChange check for the state changing, we can tell when the process has finished and carry on only if it has been successful.

With this in mind, a skeleton processReqChange function needs to check for two things. The first is the state changing to a value of 4, indicating the process complete. The second is to check the HTTP status code. You'll be familiar with common status codes like 404 (file not found) and 500 (internal server error), but the status code we're looking for is good old 200 (ok), which means everything went well. If we get both a state of 4 and an HTTP status code of 200, we can go right ahead and start processing the response. Optionally, of course, we can attempt to handle any errors at this point, if, for example, the HTTP status code was something other than 200.

function processReqChange()
{
// only if req shows "complete"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// ...processing statements go here...
} else {
alert("There was a problem retrieving
the XML data:\n" + req.statusText);
}
}
}

In Practice

I'm going to work up a practical example so we can get this going. Most web applications have some method of signing up users, and it's common to ask the user to pick a username to use for the site. Often, these need to be unique, and so a check is made against the database to see if any other user already has the username a new recruit is trying to sign up with. If you've ever signed up for a web mail account, you'll know how infuriating it is cycling around the process trying to find a username that isn't already taken. It would be really helpful if that check could be made without the user leaving the page.

The solution will involve four key elements: an XHTML form, a JavaScript function for handling the specifics of this case, our pair of generic functions (as above) for dealing with HTTP, and finally, a script on the server to search the database.
The Form

Here's the easy bit--a simple form field to collect the user's chosen username. An onblur event handler is used to fire the script. In order to display a friendly message to the user if the name is taken, I've embedded it in the form and hidden it with CSS. This should prove a little less violent than a standard JavaScript alert box.

onblur="checkName(this.value,'')" />


The CSS defines a class for hidden and also one for showing the error. Call that one error.

span.hidden{
display: none;
}

span.error{
display: inline;
color: black;
background-color: pink;
}

Handling the Input

The checkName function is used to handle the input from our form. Its job is to collect the input, decide which script on the server to present it to, invoke the HTTP functions to do the dirty work on its behalf, and then deal with the response. As such, this function has to operate in two modes. One mode receives input from the form, the other the response from the HTTP request. I'll explain the reason for this in the next section.

function checkName(input, response)
{
if (response != ''){
// Response mode
message = document.getElementById('nameCheckFailed');
if (response == '1'){
message.className = 'error';
}else{
message.className = 'hidden';
}
}else{
// Input mode
url =
'http://localhost/xml/checkUserName.php?q=' + input;
loadXMLDoc(url);
}

}

Our response is going to be easy to deal with--it'll be a string of either 1 or 0, with 1 indicating that the name is in use. Therefore, the function changes the class name of the error message so it gets displayed or hidden, depending. As you can see, the dirty work at the server is being done by a script called checkUserName.php.
HTTP Heavy Lifting

As we saw earlier, the HTTP work is being done by two functions, loadXMLDoc and processReqChange. The former can remain totally as-is for the purposes of this example, with the only modifications needed to the latter being a quick bit of DOM work.

You'll recall that by the time a successful response has been passed to processReqChange, we're no long in a position to pass any sort of return value back up the chain. Because of this, it's going to be necessary to make an explicit function call to another bit of code in order to do anything useful with the response. This is why our checkName function has to run in two modes. Therefore, the main job of processReqChange is to parse the XML coming back from the server and pass the raw values back to checkName.

However, it is important that we keep these functions generic (we may have multiple items on the page that need to make use of XMLHttpRequest), and so hard-coding a reference to checkName at this point would be foolhardy. Instead, a better design is to have the server indicate the handling function as part of its response.

standalone="yes"?>

checkName
1


Parsing such a simple response should be no problem at all.

function processReqChange()
{
// only if req shows "complete"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// ...processing statements go here...
response = req.responseXML.documentElement;

method =
response.getElementsByTagName('method')[0].firstChild.data;

result =
response.getElementsByTagName('result')[0].firstChild.data;

eval(method + '(\'\', result)');
} else {
alert("There was a problem retrieving the XML
data:\n" + req.statusText);
}
}
}

By using the responseXML property of the XMLHttpRequest object, we have a ready-made XML object we can traverse with the DOM. By grabbing content of the method element, we know which local function to execute along with the result. Once you've finished testing, it's probably a good idea to dump the else clause from the above code, enabling the function to fail silently.
The Server Script

The final piece in our jigsaw is the script on the server to accept the request, process it, and return an XML document in response. For the purposes of our example, this script looks up usernames in a database table to determine whether a name is already in use. For brevity, my example PHP script below just checks against two hard-coded names, 'Drew' and 'Fred'.

header('Content-Type: text/xml');

function nameInUse($q)
{
if (isset($q)){
switch(strtolower($q))
{
case 'drew' :
return '1';
break;
case 'fred' :
return '1';
break;
default:
return '0';
}
}else{
return '0';
}

}
?>
standalone="yes"?>'; ?>

checkName
echo nameInUse($_GET['q']) ?>



Of course, the logic used to verify the availability of the username in this script can be reused after the form is submitted to recheck that the name is available. This is an important step, since if JavaScript was not available at the client, this check would not have yet taken place. Additionally, on a busy site, a username which checked out OK at the time the user was filling the form in may have been taken by the time the form is submitted.

Perhaps as a next step, if you're interested in playing with this some more, you could add the ability for the server to return a list of suggested alternative usernames if the suggested name is taken.
read more “Very Dynamic Web Interfaces”

Using the XML HTTP Request object

Internet Explorer on Windows, Safari on Mac OS-X, Mozilla on all platforms, Konqueror in KDE, IceBrowser on Java, and Opera on all platforms including Symbian provide a method for client side javascript to make HTTP requests. From the humble begins as an oddly named object with few admirers, it's blossomed to be the core technology in something called AJAX [1].

The Object makes many things easier and neater than they other would be, and introduces some things that were otherwise impossible such as HEAD requests to see when a resource was last modified, or to see if it even exists. It makes your scripting options more flexible allowing for POST requests without having the page change, and opens up the possibility of using PUT, DELETE etc. These methods are increasingly used to provide richer Web Applications like G-Mail that use lower bandwidth and offer snappier user interaction.
Why XML HTTP Request object?

Whilst the object is called the XML HTTP Request object it is not limited to being used with XML, it can request or send any type of document, although dealing with binary streams can be problematical in javascript.
Creating the object

In Internet Explorer, you create the object using new ActiveXObject("Msxml2.XMLHTTP") or new ActiveXObject("Microsoft.XMLHTTP") depending on the version of MSXML installed. In Mozilla and Safari (and likely in future UA's that support it) you use new XMLHttpRequest() IceBrowser uses yet another method the window.createRequest() method.

This means that you need to show different script to different browsers, as what works in one, will error in another. The script below does this, and if it's not supported, the variable is set to false to allow for appropriate error messages and recovery with degrading to more normal HTTP transaction methods when the object isn't available. This degradation is important, even in IE the objects can often be blocked by slightly raised security settings (popular due to the commonly exploited holes of course). Where possible degrade, some approaches are talked about below, if you really can't, I'd recommend providing an alternative page aswell. GMail for example has said they'll be providing a less demanding version in the future, hopefully with no javascript at all, full degradation.

var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false;
}
}
if (!xmlhttp && window.createRequest) {
try {
xmlhttp = window.createRequest();
} catch (e) {
xmlhttp=false;
}
}

How do I make a request?

Making a HTTP request is very simple. You tell the XML HTTP request object what sort of HTTP request you want to make and which url you want to request. Provide a function to be called when as the request is being made, and finally what, (if any) information you want sent along in the body of the request.

The following script makes a GET request for the relative url "text.txt" (relative to the calling page) It provides the function, which checks the readyState property each time it's called and when it has the value 4 - meaning the load is complete, it displays the responseText to the user with an alert.

xmlhttp.open("GET", "test.txt",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText)
}
}
xmlhttp.send(null)

Try the example.
Making a HEAD request

With a HEAD request, a server will only return the headers of a resource, rather than the resource itself, this means you can find out the Content-Type or Last-Modified of a document, without downloading it itself.

A typical HEAD request might return something like this:

HTTP/1.1 200 OK
Server: Microsoft-IIS/4.0
Cache-Control: max-age=172800
Expires: Sat, 06 Apr 2002 11:34:01 GMT
Date: Thu, 04 Apr 2002 11:34:01 GMT
Content-Type: text/html
Accept-Ranges: bytes
Last-Modified: Thu, 14 Mar 2002 12:06:30 GMT
ETag: "0a7ccac50cbc11:1aad"
Content-Length: 52282

To make a HEAD request, you simply replace the first parameter with HEAD, and then extract the headers, either using getAllResponseHeaders or getResponseHeader("Name") to get an individual one.

xmlhttp.open("HEAD", "/faq/index.html",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.getAllResponseHeaders())
}
}
xmlhttp.send(null)

Try the example.
Using HEAD requests, to find the Last-Modified of another file.

One use of HEAD requests, is to find out when a url was modified, extending the previous example, you get something like this:

xmlhttp.open("HEAD", "/faq/index.html",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert("File was last modified on - "+
xmlhttp.getResponseHeader("Last-Modified"))
}
}
xmlhttp.send(null)

Try the example.

To format the date differently, or use something other than alert, the javascript FAQ will tell you more.
Does a url exist?

Another simple use is finding if a url exists, in HTTP there are various status codes returned by both HEAD and GET requests, 200 means success, 404 means failure, and the others mean other things. See HTTP status codes for a full explanation. using the status property of the xmlhttp object provides you this status

xmlhttp.open("HEAD", "/faq/index.html",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
if (xmlhttp.status==200) alert("URL Exists!")
else if (xmlhttp.status==404) alert("URL doesn't exist!")
else alert("Status is "+xmlhttp.status)
}
}
xmlhttp.send(null)

Try the example: with a url that exists, with a url that does not exist
Calling a server-side Script without refreshing the page

Forms are the way to "call" serverside scripts in HTML, they force the page reload, and this is often not very user friendly. Using the HTTP Request, you can call the script without refreshing the page, and still have the form "fallback" to working when the XML HTTP Request Object is not available.

<%
a=+(Request.QueryString('a')+'')
b=+(Request.QueryString('b')+'')
if (isNaN(a) || isNaN(b)) {a='';b='';total='' }
else {
total=a+b
}
acc=Request.ServerVariables('HTTP_ACCEPT')+''
if (acc.indexOf('message/x-jl-formresult')!=-1) {
Response.Write(total)
} else {
%>



+
=


<%
}
%>

Try the example page

The example above uses JScript in ASP as the server side language, the HTTP ACCEPT header is used to tell the server which response to send back - either the full page or just the result. The HTTP ACCEPT header is used to tell servers what mime-types the client will accept, normally it says things like text/html etc. Here though we tell it we only accept "message/x-jl-formresult", so the server knows it is our client (or another client, who knows about "message/x-jl-formresult") making the request.

Other methods of identifying what to return may be appropriate depending on the type of data you send to the server, or you could simply use different urls for the form submission and xmlhttp request, whatever you do, remember to have sensible fallback to the non-xml http request browsers where possible.
Using JSON as the transfer language

Whilst XML can be used to encode the information you retrieve with the object and it will be available in the responseXML property, however xml is less well supported, some browsers require that the content type of the resource is one of only 2 possible XML mime-types text/xml or application/xml for the property to be populated, and there are always the normal well formness problems you always get with XML. JSON is a good alternative, it's fast to parse, and much, much faster to access in script.

I use JSON in the Flight Routeplanner to look up information on airports, an Example with London Heathrow, you can easily parse the returned JSON into a script object using the new Function constructor, it checks the status as the script returns 404 if it fails to find an airport with that iata code.

xmlhttp.open("GET","/routeplanner/airport.1?LHR",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
if (xmlhttp.status!=404) {
var local=new Function("return "+xmlhttp.responseText)();
alert("Code - Name\n"+local[0].id+' - '+local[0].name);
} else {
alert("Airport not found");
}
}
}
xmlhttp.send(null);

Try the example.
Using XMLHTTP with GOOGLE's SOAP API

Google provides a SOAP interface to it's database. You need to register for a key that lets you make 1000 a day, to make a request. You then need to parse the returned XML.

search="Word"
xmlhttp.open("POST", "http://api.google.com/search/beta2",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText)
}
}
xmlhttp.setRequestHeader("Man", "POST http://api.google.com/search/beta2 HTTP/1.1")
xmlhttp.setRequestHeader("MessageType", "CALL")
xmlhttp.setRequestHeader("Content-Type", "text/xml")

xmlhttp.send(""+"\n\n"+" ' xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"'+
' xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"'+
' xmlns:xsd="http://www.w3.org/1999/XMLSchema">'+
' ' xmlns:ns1="urn:GoogleSearch"'+
' SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'+
'GOOGLEKEY ' xsi:type="xsd:string">'+search+' ' xsi:type="xsd:int">0 ' xsi:type="xsd:int">10 ' xsi:type="xsd:boolean">true ' xsi:type="xsd:string"> ' xsi:type="xsd:boolean">false ' xsi:type="xsd:string"> ' xsi:type="xsd:string">latin1 ' xsi:type="xsd:string">latin1'+
''+
'
')


Google is using a SOAP interface, many people think SOAP has some serious issues worth considering. REST is probably a better model as it works with the current web framework, proxies, caches etc. So whilst we can use the XML HTTP Request object to talk soap, it's probably best not to unless you have no control over what's happening on the server end. (Thanks to Dan Schmierer for pointing out an error in my script.)

By default the object can only call back to the same server, in a reduced security environment (accessed from file:// say) IE can access any domain, Mozilla can also do that if you request and are granted the appropriate permissions see "a google thread I can't get to offline!"
read more “Using the XML HTTP Request object”

Ajax Books

AJAX - Asynchronous JavaScript and XML - some books and resource links These books and resources will help you stay on top of AJAX happenings Up until now there have been few books on DHTML and only 2-3 that cover AJAX. But that will change dramatically. This will be an improvement over the Web because the otherwise excellent Web resources concntrate on specific AJAX methods and really do not spend time on the background technologies of AJAX. What gets overlooked is the details of DHTML's DOM and CSS conections. That is why we are featuring Design using JavaScript just below. Meanwhile here is a summary of what will hit the beaches: Ajax for Dummies by Steve Holzner, For Dummies Series with CD, Ajax Patterns and Best Practices by Christian Goss, Apress Books Ajax Programming with Java by Paul Deck, Brainy Software Head Rush AJAX by Brett McLaughlin, and Eric and Liz Freeman, this should be interesting as Brett has several Java+XML books under his belt and the Freemans are responsible for the excellent Head First series. Pragmatic Ajax by Justin Gehtland et alia, Pragmatic Bookshelf Professional AJAX by Nicholas Zakas et alia, Wrox Press .

Best Not-an-Ajax Book by Title
If you want the real thing right now let me recommend the following book - Modern Web Design Using JavaScript and DOM by Stuart Langridge from SitePoint for $US40. What ? No AJAX in the title ? Well, there is a blurb in the upper left corner that promises the book "covers remote scripting/AJAX". And indeed it does that and much more - it puts the AJAX phenomenon in the context of its roots - DHTML. It also looks at a range of Java Scripting alternates to pure AJAX which makes the technology more productive.

The first 4 chapters do a quick review of JavaScript, DOM, and XML coding. These refresher chapters amply convey the nature of the AJAX beast. In order to get extraordinary improvements in Web page speed and overall simplicity of the total client+server package (your total lines of code, client and server side both, should drop off notably with AJAX over ASP, PHP, JSP, etc.) - the coding on the client does become more complicated. As the author says at the outset - AJAX "is a set of Web development techniques that are mostly used in Web pages that have non-trivial input features".

The next 3 chapters show how much can be done on the client without any page refreshes required. This is the best part of the book because it has fewer server side dependencies. AJAX has the problem that all Web-based frameworks - they don't support offline operation nearly at all. But many Web applications are really "offline + online" applications. This book shows some ways the umbilical back to the server can be cut and then reconnected, for online and some offline operations.

Foundations of Ajax Books
Ajax burst onto the Web development scene by offering highly interactive, desktop-like Web applications that can be deployed through any modern Web browser without the need for special plug-ins. Ajax is built on existing Web technologies such as JavaScript, HTML, and CSS, and it is used in conjunction with your favorite server-side language. Foundations of Ajax explains how to combine these technologies effectively to implement Ajax into your new or existing Web applications. Like you, we are developers who are "in the trenches," tasked with building Web-enabled applications that provide real value to our customers. As the Web continues to grow, the demand for more expressive and engaging interfaces will continue to increase.

Much of the early hype surrounding Ajax centered on its use by Internet powerhouses such as Google and Amazon. However, just because the initial forays into Ajax were pioneered by leading software development firms doesn't mean your application wouldn't also benefit from these techniques. You already know how to develop Web applications, so this book uses specific, focused examples to teach the Ajax tools and techniques you'll need to bring your applications to life. Armed with this book and your existing development expertise, you too will be able to apply Ajax techniques to your application to enrich the end user's experience.

Buy this books see detail information:-
http://www.amazon.com/exec/obidos/ASIN/1590595823/houseoffusion/103-7137984-3343805

Professional Ajax Books
Professional Ajax discusses the range of request brokers (including the hidden frame technique, iframes, and XMLHttp) and explains when one should be used over another. You will also learn different Ajax techniques and patterns for executing client-server communication on your web site and in web applications. By the end of the book, you will have gained the practical knowledge necessary to implement your own Ajax solutions. In addition to a full chapter case study showing how to combine the book's Ajax techniques into an AjaxMail application, Professional Ajax uses many other examples to build hands-on Ajax experience. Some of the other examples include:
* web site widgets for a news ticker, weather information, web search, and site search
* preloading pages in online articles
* incremental form validation
* using Google Web APIs in Ajax
* creating an autosuggest text box

you can visit and getting more information -
http://www.wrox.com/WileyCDA/WroxTitle/productCd-0471777781.html

Book Review - Ajax Patterns and Best Practices
Christian Gross’ Ajax Patterns and Best Practices is a quality book for the intermediate to advanced ajax programmer who is looking to expand their skills. This is definitely not a beginner’s introduction to ajax, as once you get past the first three chapters or so Gross dives into some heavy duty patterns for difficult problems in ajax. The book suffers from a lack of editing and a few curious technical remarks, but overall it does a good job of covering ajax patterns and practices. Gross is obviously a fan of REST and XML, so your views on this book might depend upon how much you agree with his technical choices. Chapters one and two cover the basics of the XHR object and using the factory pattern to abstract away browser differences for the object. Chapter three covers “Content Chunking”, Gross’ term for what he admits is core to ajax - an event leading to an asynchronous request with then responds with some sort of content to inject back into the document. you see for detail information-http://ajaxian.com/by/topic/books/
read more “Ajax Books”

Ajax Tools

Many resources for easy development of Ajax Applications. You can use the Ajax Tools for easy and fast development of your web applications.

Multipurpose Tools
Gerber Blade is renowned for its high-quality sport knives and multipurpose tools for hunting, fishing, camping and other outdoor activities. Gerber Legendary Blades provides outdoor enthusiasts around the world a wide-range of unequaled cutting tools and accessories.

XI-Community and XI-Factory web tool
XI-Community/XI-Factory is the world's most advanced web tool designed to help IT and Business People with AJAX/.NET application modeling, prototyping, documentation, validation and code generation.

XI-Factory™ is the heart of the XI-Community. It is a free web tool that allows your organization to achieve a new capacity for distributed analysis that optimizes cooperation between your IT experts and business unit personnel.

It generates fully working AJAX/.NET applications using a stable and robust framework that has been used for over 6 years. XI-Factory’s workflow:-
* Import.NET Application Models from the XI-Community
* Design and customize your chosen Application Model to match your specific needs
* Generate online AJAX application prototype
* Validate the Application Model and prototype with your business users
* Generate and buy the .NET Solution matching your Application Model

Ajax IDE and ADL(Ajax Dev Library) In JoyiStar
JoyiStar WebShop is the first visual Ajax IDE. It provides an efficient OOP developing method to construct stable and convenient Rich Web applications based AJAX component.

* Main Features: 1, efficient developing tool The JoyiStar WebShop is a visualized modeling IDE (Integrated Development Environment). It follows the OOP methodology and is constructed by many components which are useful to accelerate application development process. In other words, it helps to produce mature and complicate Rich Web applications at certain high level. 2, AJAX development tools The JoyiStar WebShop is an AJAX development tools to develop business-critical web applications and it offers optimizing power of AJAX technology. 3, Encapsulated Web Components - avoid your pain The JoyiStar WebShop provides many web components to attain powerful functions such as dynamically generate master-details, user interfaces, web report etc. 4,Support source insight... 5, Simple, Secure, Standards based Pull-drag developing - program in the mode of your choice. Cross-Platform - support all major browsers at present. Integration - integrates with existing server-side codes and services.


Ajax Toolkit Framework for Eclipse
Ajax Toolkit Framework is a plugin for general-purpose (but Java-focused), open-source, Eclipse IDE. A technology that assists in constructing Eclipse framework support for AJAX Toolkits and provides enhanced DHTML/Javascript IDE features for AJAX developers.

What is AJAX Toolkit Framework?
AJAX Toolkit Framework (ATF) provides extensible tools for building IDEs for the many different AJAX (asynchronous JavaScript and XML) run-time environments (such as Dojo, Zimbra, etc.). This technology also contains features for developing, debugging, and testing AJAX applications. The framework provides enhanced JavaScript editing features such as edit-time syntax checking; an embedded Mozilla Web browser; an embedded DOM browser; and an embedded JavaScript debugger.

An additional and unique aspect of the framework is the Personality Builder function, which assists in the construction of IDE features for arbitrary AJAX run-time frameworks and thus adds to the supported set of run-time environments in the ATF.

AJAX Toolkit Framework is part of the Emerging Technologies Toolkit (ETTK), a special collection of emerging technologies from IBM's software development and research labs. This technology has also been proposed as an Eclipse Incubation Project.

How does it work?
This technology is based largely upon the Eclipse Web Tools Project. ATF enables support of DOM browsing and JavaScript debugging by using Mozilla XULrunner to embed the Mozilla browser component (Gecko) in the Eclipse framework.
read more “Ajax Tools”

Ajax File Upload Example



This application illustrates how to upload a file using servlet through the Ajax technology.

In this example you simply create a file Upload application using ajax just follows by these points:

* Create a simple HTML form for file upload
* Set the target to an iFrame which is on the actual page but not visible
* Call a JavaScript function on form submit to call the servlet
* And the servlet finishes the all upload process.

To understand the way this works I think it is easiest to break it down into parts:

1. A file upload extention that counts bytes as they are uploaded
2. An interface that monitors the progress of something running on the server
3. AJAX to pull the monitoring into the current screen



The Entire Application is as follows:





Source Code of fileUpload.html


Ajax File Upload




target="uploadFrame"
action="example/FileUploadServlet" onsubmit="ajaxFunction()">


"Upload" />






style="visibility: hidden; position: absolute; top: 100px;">










 








Source Code of FileUploadServlet.java
package fileupload;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServlet;

import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import javax.servlet.ServletException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class FileUploadServlet extends HttpServlet implements Servlet {
private static final long serialVersionUID = 2740693677625051632L;

public FileUploadServlet(){
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
FileUploadListener listener = null;
StringBuffer buffy = new StringBuffer();
long bytesRead = 0, contentLength = 0;

if (session == null){
return;
} else if (session != null){
listener = (FileUploadListener)session.getAttribute("LISTENER");

if (listener == null){
return;
} else {
bytesRead = listener.getBytesRead();
contentLength = listener.getContentLength();
}
}

response.setContentType("text/xml");

buffy.append("\n");
buffy.append("\n");
buffy.append("\t" + bytesRead + "\n");
buffy.append("\t" + contentLength + "\n");

if (bytesRead == contentLength) {
buffy.append("\t\n");
session.setAttribute("LISTENER", null);
} else {
long percentComplete = ((100 * bytesRead) / contentLength);
buffy.append("\t" + percentComplete + "\n");
}
buffy.append("
\n");
out.println(buffy.toString());
out.flush();
out.close();
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
FileUploadListener listener = new FileUploadListener();
HttpSession session = request.getSession();
session.setAttribute("LISTENER", listener);
upload.setProgressListener(listener);
List uploadedItems = null;
FileItem fileItem = null;
String filePath = "c:\\temp";

try {
uploadedItems = upload.parseRequest(request);
Iterator i = uploadedItems.iterator();

while (i.hasNext()) {
fileItem = (FileItem) i.next();
if (fileItem.isFormField() == false) {
if (fileItem.getSize() > 0) {
File uploadedFile = null;
String myFullFileName = fileItem.getName(), myFileName = "", slashType =
(myFullFileName.lastIndexOf("\\") > 0) ? "\\" : "/";
int startIndex = myFullFileName.lastIndexOf(slashType);
myFileName = myFullFileName.substring(startIndex + 1, myFullFileName.length());
uploadedFile = new File(filePath, myFileName);
fileItem.write(uploadedFile);
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}



Source Code of FileUploadListener.java
package fileupload;

import org.apache.commons.fileupload.ProgressListener;

public class FileUploadListener implements ProgressListener{
private volatile long bytesRead = 0L, contentLength = 0L, item = 0L;

public FileUploadListener() {
super();
}

public void update(long aBytesRead, long aContentLength, int anItem) {
bytesRead = aBytesRead;
contentLength = aContentLength;
item = anItem;
}

public long getBytesRead() {
return bytesRead;
}

public long getContentLength() {
return contentLength;
}

public long getItem() {
return item;
}
}



Download Complete Source Code
read more “Ajax File Upload Example”

Ajax Registration Program




In this Ajax Registration program you will learn how to validate the user registration through ajax call and then display the alert massage if no values are provided in the username and password fields.

When a user input user Id and password and press Register button , method 'call_Register()' will make ajax call. If the value returned from the server is "yes" the alert box will show 'Welcome for Register' otherwise it will show ' the Invalid Id/password please enter the Id/password!'.

Example of Ajax Registration program:




Ajax Registratiion program




































Registration
Login id:
Password:

style="background-color:#FFE9D2;color:#0000FF; border-color:#99CC33">







Here this code support the Register.php for Ajax Registration program:
$loginid=$_GET["loginid"];
$password=$_GET["password"];
if( $password == "" || $loginid == "" || ($loginid == "" && $password == "") ){
echo "no";
}
else{
echo "yes";
}
?>
read more “Ajax Registration Program”

Ajax Login Example

In this program you will learn how to validate the user and show alert message if user name or password are not correct. These days almost all the e-comm applications requires authentication before accessing the secured part of the web site.

Search Tutorials:

Software Solutions and Services



Google Custom Search:


Advertise Here
Website Designing Services

Web Designing Packages From $150!

Website Designing Company Web Hosting

Website Designing Quotation
Ajax Login Program



In this program you will learn how to validate the user and show alert message if user name or password are not correct. These days almost all the e-comm applications requires authentication before accessing the secured part of the web site. In this program we will show how you can send ajax request to authenticate the user.

When a user input username and password and press Login button, 'call_login()' function is called. This method sends ajax request to server (login.php) to validate the user. We have hardcoded the authonication mechanism e.g. if you enter login name admin and password admin then the program will show you success message. Otherwise it will show login failed message. You can change the authentication logic in the page and easily authenticate use from database.

Example of Ajax login Program :
























Login
User
Name:
Password:









Here is the code for login.php page:
$username=$_GET["username"];
$password=$_GET["password"];
if($username=="admin" && $password=="admin"){
echo "yes";
}else{
echo "No";
}
?>
read more “Ajax Login Example”

Ajax Multiplication Program



Ajax is a web development technique where you can send the request to server without refreshing the page. In this section, you will learn how to multiply two values and display the result on the page. This program calls the method 'callmultiply()' for the multiplying the values entered by user. The multiplication operation is performed in the 'multiply.php' page at serverside. The 'callmultiply()' sends the numbers as url string by calling the 'postRequest()' method. The 'postRequest()' method generates Ajax call to serverside script 'multiply.php'. And finally 'updatepage()' method updates the multiplication result on the html page.

Example of Ajax multiplication program:


Ajax Multiply Example




Ajax Example









read more “Ajax Multiplication Program”

Ajax First Example - Print Date and Time



In this section we will create a simple Ajax Application for displaying the current date and time. Date and time information are retrieved asynchronously from the server side php script. Our HTML page calls serverside php script to retrieve the today's date. Once the time data is retrieved from the server, it uses javascript and css to display the time on the HTML page.





Here is the code of HTML File:




Ajax Example







Ajax Example



 This very simple Ajax Example retrieves the

current date and time from server and shows on the form. To view the current

date and time click on the following button.





 
type="button" onclick='JavaScript:showCurrentTime()' name="showdate">














When use clicks on the "Show Time" button, the showCurrentTime() is called. The the function showCurrentTime() calls the time.php using Ajax and then updates the time values retrieved from server.
read more “Ajax First Example - Print Date and Time”

The Role of AJAX in enhancing the user experience on the Web ( Sagar G Arlekar - June 2006

AJAX is not a new technology but a combination of several existing technologies in a new way. These include HTML, CSS, DOM, XML, XSLT, XMLHttpRequest and Javascript. The acronym AJAX stands for Asynchronous Javascript and XML. AJAX is based on open standards supported by many browsers and platforms. AJAX is a new paradigm for building web application.

AJAX applications eliminate the start-stop-start-stop nature of traditional web pages hence allow web application to look and behave like the desktop ones, of course to a limited extent. AJAX allows pages to request small bits of information from the server instead of entire pages. This incremental updating of pages eliminates the page refresh problem and slow response that have plagued Web applications since their inception.

AJAX has received tremendous industry recognition and support. The major software giants and web portals have adopted it. A large number of AJAX toolkits and libraries are available for free. AJAX does have its limitation but most of them can be overcome by integrating AJAX with other technologies whenever required.

AJAX is here to change the user experience on desktop as well as on mobile devices.

Rich Internet Applications

According to Wikipedia Rich Internet Applications (RIA) are web applications that have the features and functionality of traditional desktop applications. RIA's transfer the processing necessary for the user interface to the web client but keep the bulk of the data back on the application server.

Traditional web applications centered all activity around a client-server architecture with all processing done on the server, and the client only displaying static content. The biggest drawback with this system is that all interaction must pass through the server, which requires data to be sent to the server, the server to respond, and the page to be reloaded on the client with the response. Most traditional web applications have clumsier and difficult to use interfaces compared to desktop ones. The primary difference between a RIA and traditional web applications is the amount and quality of interaction between the user and the interface. An RIA can use a wider range of controls to improve users’ interaction allowing efficient interactions, better error management, feedback and overall user experience. Another benefit of RIAs is that data can be cached in the client, allowing a vastly more responsive user interface and fewer round trips to the server.

Some of the features and benefits delivered by RIA's are listed below

a) Allows feedback, confirmation and errors messages to be displayed on same page/view.

b) Wider variety of controls e.g. sliders, date pickers, windows, tabs, spinners etc.

c) No installation, just an AJAX enabled browser required

d) Higher immunity to viruses and piracy.

e) Reduced load on server resources as processing is distributes over server and client

f) Lowered application development and deployment costs

g) Reduction in network traffic due to more intelligent client and selective data request

The most common technologies used for building RIA's are Java applets and web start, Adobe Flash and Flex, and AJAX. Efforts are being made to make AJAX work with the other mentioned technologies. Adobe Systems has released libraries to help developers bridge Adobe Flash and Flex technology with AJAX. Similarly libraries are available to integrate AJAX with Java,.NET,PHP,Python,Perl,Ruby and other backend technologies.

What can AJAX do?

To start with let me tell the readers that this entire document was composed online using an AJAX powered word processor available at www.writely.com

AJAX is playing a crucial role in making Web 2.0 promises a reality. Some of the features of web 2.0 are

a) Use of Web as the platform

b) Software delivered as a service instead of packaged software

c) Cost-effective scalability

d) Architecture with user participation

AJAX interfaces are a key component of many Web 2.0 applications. Google, Yahoo, Microsoft, Amazon and many others have embraced AJAX.

Google services like Maps, Gmail, Suggest, Reader use it. Google Maps, which is considered as one of the most impressive and popular AJAX based application, allows user to zoom in and out and scroll the map in four directions very much like a desktop application. User can drag the map on screen with the mouse pointer and double click to center. All this with no clicking and waiting for graphics to reload each time you want to view the adjacent parts of a map. Gmail uses AJAX for spell-check, auto save, new email check and other functions. In Google suggest suggestions are provided in real time as the user types the search query.

Yahoo's Flickr and instant search use AJAX. In Flickr the text-editing and tagging interface uses it. Instant search gives user the result as he/she is typing the query. Yahoo frontpage too has been AJAXified.

Windows Live is a free AJAX virtual desktop. Some of its features are search, news, maps, email integration, instant messenger, contact management tool etc. More features can be included through the use of third party 'Gadgets'.

Meebo is a web based instant messenger client, it supports Yahoo, Gtalk, MSN and AIM protocols. Writely, Zoho, gOffice, AjaxOffice are AJAX based online word processors; some are full-fledged office suits. Digg is a technology news website that combines social bookmarking, blogging, RSS, and non-hierarchical editorial control. Travbuddy lets users create travel journals and share travel experiences, reviews and photos. This application also uses Google Maps. Pageflakes, Netvibes and Protopage are free startpages.

Zimbra is an AJAX based collaboration suit. Kiko and Calendarhub are online calendars. Pixoh is an online photo editing application

The impact of AJAX on user experience
AJAX user interfaces are highly responsive giving users the feeling that changes are instantaneous. It also introduces multiple segments of interactivity on the same page. User may submit a form and immediately after concentrate on some text or click on a menu item in some other segment. Even in case of an error in one segment other segments can stay usable. AJAX applications usually avoid the need of horizontal and vertical scrollbars, this adds to user convenience.

Existing AJAX applications can be categorized into two types 1) partially AJAXed - here AJAX is used to provide certain functionalities e.g. Flickr and 2) fully AJAXed - here AJAX is necessary for functionalities as well as for user-interface e.g. Meebo, Google Maps, Windows Live

The way users use fully AJAXed applications is very different from their traditional web experience. In these applications the concept of web pages breaks down, surfing a site or using an applications is not just clicking links and loading fresh pages. In some applications the response may result in changes to small/certain parts of the current view, the URL in the address bar remains unchanged and the Back, Forward, Reload and Bookmark buttons are rendered meaningless. The browser is not certain to show the previous state of the application on hitting Back/Forward buttons. Users need to adapt to this change in browser behavior.

Some of the processes/elements in user experience which have undergone AJAXification are mentioned below

a) Hierarchical tree navigation - users find it irritating to navigate trees in Directories and Discussion threads, AJAX makes expansion/contraction of tree nodes smooth without making the user wait for the new page to load

b) Form value check - as the user fills in a online form an AJAX call could be made to the server to do tasks like checking availability of user name, measure strength of password, populate drop-down boxes further down based on data already entered. Also auto-completion and spell-check features can be provided

c) Rapid user-user communication - browser based chat applications and games can be built without the need to manually refresh the page to get current data/state

d) Data filtering and rearranging - this include applying a filter, sorting by date or some particular column values, relocate iframes, divs and page elements

e) Server-side pushes - AJAX enables simulation of server-side push technology using polling

AJAX on mobile

Pocket PC and Smartphone Devices (2003 and later) support AJAX.

Opera Software has released Opera Platform SDK, a kit for developing and running software on mobile phones. This SDK will allow development of AJAX based rich mobile applications. In addition the Opera Platform SDK will help developers adapt existing content and web applications to run on mobile phones.

By storing an AJAX application on the mobile phone and allowing XML-communication with a Web-server, the traditional bandwidth constraints become less of an issue. This also enables transparent updating of information pushed to the mobile phone.

With increasing processor power and wireless network speeds AJAX is sure to play an important role in enhancing mobile user experience.
read more “The Role of AJAX in enhancing the user experience on the Web ( Sagar G Arlekar - June 2006”