08.01.2015 Views

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 11 ■ <strong>AJAX</strong> APPLICATIONS AND EMPOWERING THE WEB USER EXPERIENCE 263<br />

The final piece of the puzzle is the callback. When you specify a callback function,<br />

the XMLHttpRequest object will call it four times, setting the readyState property to the<br />

values 1, 2, 3, <strong>and</strong> 4, respectively. These correspond to the following states:<br />

1: Communication open<br />

2: Message sent to server<br />

3: Payload downloading from server<br />

4: Payload download complete<br />

The responseText property contains the returned values from the server.<br />

So, if you are only interested in updating the page when the server has completed its<br />

operation <strong>and</strong> sent its payload, then check the readyState for the value 4. You can see this<br />

in action here:<br />

function h<strong>and</strong>leUpdate()<br />

{<br />

var ansDiv = document.getElementById("ans");<br />

if(ajaxRequest.readyState == 4)<br />

{<br />

ansDiv.innerHTML = ajaxRequest.responseText;<br />

}<br />

}<br />

This checks the readyState of the ajaxRequest, <strong>and</strong> when it is 4, it takes the<br />

responseText <strong>and</strong> loads it into the element that is assigned to contain the answer.<br />

If you run this application, you can see the effect. As you type in the text boxes, the<br />

Ajax code will execute, calling the server <strong>and</strong> processing the return, loading it into the<br />

answer , <strong>and</strong> giving a much more fluid user experience.<br />

Again, as this is a simple case (multiplying two numbers), you could argue that you<br />

don’t need a server, <strong>and</strong> thus don’t need Ajax—but it indicates the methodology that you<br />

would use in a scenario where the mathematical functions may be too complex to do in<br />

JavaScript, or may involve proprietary algorithms, as is the case with many financial analytics<br />

calculations.<br />

You can see it in action in Figure 11-4.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!