| By Corey Gilmore, Jason Blum, Phil McCarthy | Article Rating: |
|
| April 24, 2007 08:00 AM EDT | Reads: |
6,335 |
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.
Published April 24, 2007 Reads 6,335
Copyright © 2007 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
About 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.
About 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.
About 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.
- AJAX World RIA Conference & Expo Kicks Off in New York City
- What is Web 3.0?
- AJAXWorld RIA Conference & Expo 2009 West: Call for Papers
- AJAX and RIA 2009: More Choices, Tough Decisions
- Ulitzer’s Amazing First 30 Days in Public Beta
- SYS-CON Announces Government IT Conference & Expo
- RIAs for Web 3.0 Using the Microsoft Platform
- REA Is Where RIA Becomes the Norm
- Why an Application Grid?
- 2nd International Cloud Computing Expo New York Photo Album
- AJAX World RIA Conference & Expo Kicks Off in New York City
- What is Web 3.0?
- Developing Rich Client Applications Using Swing - II
- AJAXWorld RIA Conference & Expo 2009 West: Call for Papers
- AJAX and RIA 2009: More Choices, Tough Decisions
- AJAX World RIA Conference Awards Announced
- WebORB Launched for Flex, Flash, AJAX and Silverlight
- Appcelerator Revolutionizes UI Prototyping
- Adobe Takes LiveCycle into the Cloud
- Ulitzer’s Amazing First 30 Days in Public Beta
- Building a Drag-and-Drop Shopping Cart with AJAX
- What Is AJAX?
- Google Maps! AJAX-Style Web Development Using ASP.NET
- Flashback to January 2006: Exclusive SYS-CON.TV Interviews on "OpenAjax Alliance" Announcement
- AJAXWorld Conference & Expo to Take Place October 2-4, 2006, at the Santa Clara Convention Center, California
- AJAX Sponsor Webcasts Are Now Available at AJAXWorld Website
- How and Why AJAX, Not Java, Became the Favored Technology for Rich Internet Applications
- "Real-World AJAX" One-Day Seminar Arrives in Silicon Valley
- AJAXWorld University Announces AJAX Developer Bootcamp
- AJAX Support In JadeLiquid WebRenderer v3.1






































