O'Reilly logo

Prototype and Scriptaculous: Taking the Pain out of JavaScript by Chris Angus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.7. Ajax

Prototype simplifies working with Ajax via Ajax.Request and related objects, which simplify by using the XmlHttpRequest object. To make an Ajax call, we create an Ajax.Request object, passing in the URL of the web service along with configuration options:

var ajaxRequest = new Ajax.Request(url, options)
Method HTTP method (GET, POST, PUT, etc)
Parameters String holding URL parameters
Aynchronous True/false
postBody The body to post if the method is POST
requestHeaders Flattened array of key value pairs for header values
onComplete Callback
onLoaded Callback
onLoading Callback
onInteractive Callback
onUninitialized Callback
onSuccess Callback
onFailure Callback
onException Callback

An example of using Ajax is given below. As this document is about JavaScript and not web services, we will use a static document as the server to allow testing. The file is called rate.json and contains:

({rate:1.85})
Example 3-3. Calling a JSON service using Ajax
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Script-Type" content="text/javascript"/> <title>Using Scriptaculous</title> <script src="js/prototype.js" ></script> </head> <body> <script type="text/javascript"> function callbackComplete(from,to,request) { var json = request.responseText; var obj = eval(json ); alert('the rate from '+from+' to '+to+' is currently ' + obj.rate); } function ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required