Welcome!

AJAX & REA Authors: Chris Wiborg, Andreas Grabner, Carmen Gonzalez, Brad Abrams, Deborah Strickland

Related Topics: AJAX & REA

AJAX & REA: Article

Real-World AJAX Book Preview: AJAX Without a Server-side Framework

Real-World AJAX Book Preview: AJAX Without a Server-side Framework

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs for the special pre-order price, click here for more information. Aimed at everyone from enterprise developers to self-taught scripters, Real-World AJAX: Secrets of the Masters is the perfect book for anyone who wants to start developing AJAX applications.

AJAX Without a Server-side Framework
If you already have AJAX-friendly web services in place, or have a complex site with a framework that's not readily modified, you may find it easier to use a client-side framework like Prototype.js or jQuery. We'll assume that you have AJAX-friendly web services. Let's try an example using our PHP web service to add two numbers.

Listing 6.9 Building a Sample Page To Access the 'Add' Web Service

<HTML>
<HEAD>
<SCRIPT>
function addNumbers() {
     // Create a variable to hold our XMLHttpRequest
     var req = null;

     // Now create our request object.
     // For Safari, Mozilla, Opera 7.60b+
     // and other browsers supporting XMLHttpRequest
     if( window.XMLHttpRequest ) {
     req = new XMLHttpRequest ();
   } else if( window.ActiveXObject ) { // IE
     req = new ActiveXObject('Microsoft.XMLHTTP');
   } else {
     // Unsupported browser.
     // This should be handled more gracefully.
     alert('Your browser does not support XMLHTTP objects (Ajax).');
     return 0;
   }

   // Create a callback function to handle our response.
   // It's important to create this before you submit your request, otherwise
   // the request may return before the script is ready to handle it.
   req.onreadystatechange = function() {
     // If readyState is 4 then the request has completed.
     // 200 the HTTP status code for a successful request.
     // This combination tells us everything worked, and we can continue.
     if (req.readyState == 4 && req.status == 200) {
       // When we have a response we'll send the response to a function
       // that will write it to the page.
       var response = eval( '(' + req.responseText + ')' );
       writeResponse("The sum of " + response['numbers'] + ' is ' + response['sum']);
     }
   }

   // get the handle to our text field so we can retrieve it's contents.
   var num = getElem('num');

   // Open our request. This takes 3 arguments, the method to use, the URL and a
   // boolean to determine if the request should be asynchronous.
   req.open('GET', 'http://realworldajax/php/add.php?numbers=' + num.value +
'&output=json', true);

   // Send our request.
   // The send function takes one argument, the content to send.
   // Since we're not using POST we don't have any content, hence the null.
   req.send(null);
}

// This function creates a new PRE tag and fills it with the text sent.
// It then appends the tag to the BODY of the HTML document.
function writeResponse(txt) {
     var bod = document.getElementsByTagName('body')[0];
     var pre = document.createElement('pre');
     pre.innerHTML = txt;
     bod.appendChild(pre);
   }

   // Provide an ID and this will return a handle to the object.
   function getElem( szSrcID ) {
     return document.layers ? document.layers[szSrcID] :
     document.getElementById ? document.getElementById(szSrcID) :
     document.all[szSrcID];
   }

   </SCRIPT>
   </HEAD>
   <BODY>
     <h4>Enter space delimited numbers to add</h4>
     <label for=”num”>Numbers</label> <input type=”text” value=”” name=”num” id=”num” /><br
/>
     <input type=”button” onclick=”addNumbers()” value=”Click to Add” />
</BODY>
</HTML>

What It Does
Our HTML is fairly simple. We have an input field to hold our numbers and a button. Clicking the button calls the JavaScript function addNumbers(). Figure 6.1 shows the blank form.

addNumbers() creates our XMLHttpRequest object and the callback function that will handle the returned data. Then it sends the value of the text field to our Web service:

http://realworldajax/php/add.php?numbers=VALUE_OF_TEXT_FIELD&output=json

The Web service processes the numbers and returns the input in JSON format. The input is processed and then appended to the document.

Figure 6.2 shows the example after addNumbers() is called twice.

While this is actually using AJAX, it's not that impressive. Let's try creating a new Web service that's a bit more useful.

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs, click here to order.

More Stories By Corey Gilmore

Corey Gilmore is the president of CFG Consulting, Inc., specializing in developing rich internet applications with ColdFusion, PHP and Ajax for the Federal government and Fortune 100 clients. He guiltily enjoys designing and implementing low-cost, high performance business continuity plans using VMware ESX server. As the former Director of Information Technology for the United States Senate Democratic Leadership, he designed and implemented a continuity of operations plan to ensure Senate business continuity in the event of a disaster. Corey can be reached at cfgci.com.

More Stories By Jason Blum

Jason Blum is principal engineer with the advanced technologies development team in the United States Senate, Office of the Sergeant at Arms. Formerly the lead administrator of the Senate’s shared Web hosting environment, Jason now designs and manages the implementation of schema and pattern-centric solutions for Senate offices in XML, ColdFusion, Flex, and .NET. He is a Certified Advanced ColdFusion developer with a BA in philosophy, Masters Degrees in philosophy of education and in IT, and an intermediate certification in Hungarian from itk.hu.

More Stories By Phil McCarthy

Philip McCarthy is a UK-based software development consultant
specializing in J2EE and Web technologies. An early adopter of rich
browser-based client development, he has several years' experience of integrating Ajax technologies into enterprise Java frameworks, gained on projects in the financial services, telecoms, and digital media sectors. Philip is also the author of the "Ajax for Java Developers" series for IBM developerWorks, and blogs about software development at chimpen.com.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.