AJAX

  Home  World Wide Web  AJAX


“Learn AJAX programming with thousands of AJAX examples here in AJAX Interview Questions and Answers.”



61 AJAX Questions And Answers

21⟩ What kinds of applications is Ajax best suited for?

We don’t know yet. Because this is a relatively new approach, our understanding of where Ajax can best be applied is still in its infancy. Sometimes the traditional web application model is the most appropriate solution to a problem.

 192 views

23⟩ What about applets and plugins?

Don't be too quick to dump your plugin or applet based portions of your application. While AJAX and DHTML can do drag and drop and other advanced user interfaces there still limitations especially when it comes to browser support. Plugins and applets have been around for a while and have been able to make AJAX like requests for years. Applets provide a great set of UI components and APIs that provide developers literally anything.

Many people disregard applets or plugins because there is a startup time to initialize the plugin and there is no guarantee that the needed version of a plugin of JVM is installed. Plugins and applets may not be as capable of manipulating the page DOM. If you are in a uniform environment or can depend on a specific JVM or plugin version being available (such as in a corporate environment) a plugin or applet solution is great.

One thing to consider is a mix of AJAX and applets or plugins. Flickr uses a combination of AJAX interactions/DHTML for labeling pictures and user interaction and a plugin for manipulating photos and photo sets to provide a great user experience. If you design your server-side components well they can talk to both types of clients.

 183 views

24⟩ How Ajax is Different?

An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary — an Ajax engine — between the user and the server. It seems like adding a layer to the application would make it less responsive, but the opposite is true.

Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine — written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for both rendering the interface the user sees and communicating with the server on the user’s behalf. The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something.

 172 views

26⟩ How do I access data from other domains to create a mashup with Java?

From your JavaScript clients you can access data in other domains if the return data is provide in JSON format. In essence you can create a JavaScript client that runs operates using data from a different server. This technique is know as JSON with Padding or JSONP. There are questions as to whether this method is secure as you are retrieving data from outside your domain and allowing it to be executed in the context of your domain. Not all data from third parties is accessible as JSON and in some cases you may want an extra level of protection. With Java you can provide a proxy to third party services using a web component such as a servlet. This proxy can manage the communication with a third party service and provide the data to your clients in a format of your choosing. You can also cache data at your proxy and reduce trips to service. For more on using a Java proxy to create mashups see The XmlHttpProxy Client for Java.

 194 views

27⟩ How do we create a thread to do AJAX polling?

JavaScript does not have threads. JavaScript functions are called when an event happens in a page such as the page is loaded, a mouse click, or a form element gains focus. You can create a timer using the setTimeout which takes a function name and time in milliseconds as arguments. You can then loop by calling the same function as can be seen in the JavaScript example below.

function checkForMessage() {

// start AJAX interaction with processCallback as the callback function

}

// callback for the request

function processCallback() {

// do post processing

setTimeout("checkForMessage()", 10000);

}

Notice that the checkForMessage will continue to loop indefinitely. You may want to vary the increment the interval based on activity in the page or your use cases. You may also choose to have logic that would break out of the loop based on some AJAX response processing condition.

 185 views

28⟩ How do we debug JavaScript?

There are not that many tools out there that will support both client-side and server-side debugging. I am certain this will change as AJAX applications proliferate. I currently do my client-side and server-side debugging separately. Below is some information on the client-side debuggers on some of the commonly used browsers.

* Firefox/Mozilla/Netscape - Have a built in debugger Venkman which can be helpful but there is a Firefox add on known as FireBug which provides all the information and AJAX developer would ever need including the ability to inspect the browser DOM, console access to the JavaScript runtime in the browser, and the ability to see the HTTP requests and responses (including those made by an XMLHttpRequest). I tend to develop my applications initially on Firefox using Firebug then venture out to the other browsers.

* Safari - Has a debugger which needs to be enabled. See the Safari FAQ for details.

* Internet Explorer - There is MSDN Documentation on debugging JavaScript. A developer toolbar for Internet Explorer may also be helpful.

While debuggers help a common technique knowing as "Alert Debugging" may be used. In this case you place "alert()" function calls inline much like you would a System.out.println. While a little primitive it works for most basic cases. Some frameworks such as Dojo provide APIs for tracking debug statements.

 177 views

30⟩ How do we handle concurrent AJAX requests?

With JavaScript you can have more than one AJAX request processing at a single time. In order to insure the proper post processing of code it is recommended that you use JavaScript Closures. The example below shows an XMLHttpRequest object abstracted by a JavaScript object called AJAXInteraction. As arguments you pass in the URL to call and the function to call when the processing is done.

function AJAXInteraction(url, callback) {

var req = init();

req.onreadystatechange = processRequest;

function init() {

if (window.XMLHttpRequest) {

return new XMLHttpRequest();

} else if (window.ActiveXObject) {

return new ActiveXObject("Microsoft.XMLHTTP");

}

}

function processRequest () {

if (req.readyState == 4) {

if (req.status == 200) {

if (callback) callback(req.responseXML);

}

}

}

this.doGet = function() {

req.open("GET", url, true);

req.send(null);

}

this.doPost = function(body) {

req.open("POST", url, true);

req.setRequestHeader("Content-Type", "

application/x-www-form-urlencoded");

req.send(body);

}

}

 187 views

34⟩ Is Ajax just another name for XMLHttpRequest?

No. XMLHttpRequest is only part of the Ajax equation. XMLHttpRequest is the technical component that makes the asynchronous server communication possible; Ajax is our name for the overall approach described in the article, which relies not only on XMLHttpRequest, but on CSS, DOM, and other technologies.

 213 views

36⟩ How do I provide internationalized AJAX interactions?

Just because you are using XML does not mean you can properly send and receive localized content using AJAX requests. To provide internationalized AJAX components you need to do the following:

* Set the charset of the page to an encoding that is supported by your target languages. I tend to use UTF-8 because it covers the most languages. The following meta declaration in a HTML/JSP page will set the content type:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

* In the page JavaScript make sure to encode any parameters sent to the server. JavaScript provides the escape() function which returns Unicode escape strings in which localized text will appear in hexadecimal format. For more details on JavaScript encoding see Comparing escape(), encodeURI(), and encodeURIComponent().

* On the server-side component set the character encoding using the HttpServletRequest.setCharacterEncoding() method. Before you access the localized parameter using the HttpServletRequest.getParameter() call. In the case of UTF this would be request.setCharactherEncoding("UTF-8");.

A server-side component returning AJAX responses needs to set the encoding of the response to the same encoding used in the page.

response.setContentType("text/xml;charset=;UTF-8");

response.getWriter().write(" invalid ");

 168 views

37⟩ How do I send an image using AJAX?

While it may appear that images are being sent when using AJAX with an application like Google Maps what is really happening is that the URLs of images are being send as the response of an AJAX request and those URLs are being set using DHTML.

In this example an XML document is returned from an AJAX interaction and the category bar is populated.

<categories>

<category>

<cat-id>1</cat-id>

<name>Books</name>

<description>Fun to read</description>

<image-url>books_icon.gif</image-url>

</category>

<category>

<cat-id>2</cat-id>

<name>Electronics</name>

<description>Must have gadgets</description>

<image-url>electronics.gif</image-url>

</category>

</categories>

Notice that the image-url element contains the location of the URL for the image representing a category. The callback method of an AJAX interaction will parse the response XML document and call the addCategory function for each category included in the response XML document. The addCategory function looks up a table row element "categoryTable" in body of the page and adds a row to the element which contains the image.

 162 views

38⟩ How do I submit a form or a part of a form without a page refresh?

When creating a form make sure that the "form" element "onSubmit" attribute is set to a JavaScript function that returns false.

<form onSubmit="doAJAXSubmit();return false;" >

<input type="text" id="tf1" />

<input type="submit" id="submit1" value="Update"/>

</>

You can also submit data by associating a function with a form button in a similar way.

<form onSubmit="doAJAXSubmit();return false;" >

<input type="text" id="tf1" />

<input type="button" id="button1" onClick="doAJAXSubmit()" value="Update"/>

</>

Note that the form "onSubmit" attribute is still set. If the user hits the enter key in the text field the form will be submitted so you still need to handle that case.

When updating the page it is recommend you wait to make sure that the AJAX update of the form data was successful before updating the data in the page. Otherwise, the data may not properly update and the user may not know. I like to provide an informative message when doing a partial update and upon a successful AJAX interaction I will then update the page

 153 views

39⟩ How does HTML_AJAX compare with the XAJAX project at Sourceforge?

XAJAX uses XML as a transport for data between the webpage and server, and you don't write your own javascript data handlers to manipulate the data received from the server. Instead you use a php class and built in javascript methods, a combination that works very similiar to the HTML_AJAX_Action class and haSerializer combo. XAJAX is designed for simplicity and ease of use.

HTML_AJAX allows for multiple transmission types for your ajax data - such as urlencoding, json, phpserialized, plain text, with others planned, and has a system you can use to write your own serializers to meet your specific needs. HTML_AJAX has a class to help generate javascript (HTML_AJAX_Helper) similiar to ruby on rail's javascript helper (although it isn't complete), and an action system similiar to XAJAX's "action pump" that allows you to avoid writing javascript data handlers if you desire.

But it also has the ability to write your own data handling routines, automatically register classes and methods using a server "proxy" script, do different types of callbacks including grabbing remote urls, choose between sync and async requests, has iframe xmlhttprequest emulation fallback capabilities for users with old browsers or disabled activeX, and is in active development with more features planned (see the Road Map for details)

 173 views

40⟩ How do I handle the back and forward buttons in AJAX?

While you could go out and create a custom solution that tracks the current state on your application I recommend you leave this to the experts. Dojo addresses the navigation in a browser neutral way as can be seen in the JavaScript example below.

function updateOnServer(oldId, oldValue,

itemId, itemValue) {

var bindArgs = {

url: "faces/ajax-dlabel-update",

method: "post",

content: {"component-id": itemId, "component-value":

itemValue},

mimetype: "text/xml",

load: function(type, data) {

processUpdateResponse(data);

},

backButton: function() {

alert("old itemid was " + oldId);

},

forwardButton: function(){

alert("forward we must go!");

}

};

dojo.io.bind(bindArgs);

}

The example above will update a value on the server using dojo.io.bind() with a function as a property that is responsible for dealing with the browser back button event. As a developer you are capable of restoring the value to the oldValue or taking any other action that you see fit.

 214 views