This example performs a simple calculation. In practice, it would be done on the client; it's that simple. But, it demonstrates an AJAX process using an iframe.
Enter two numbers, select the operation you want, and then click "Calc". Try changing your choices. Subsequent RPCs are generally faster than the first depending on browser settings.
What's Happening: The operands and operation choice are sent to the server. The PHP script on the server performs the calculation and returns the answer.
Not real exciting, I know. This could have been done on the client, but imagine, if you will, a more complicated calculation. One that uses tables to lookup values as well as arithmetic.
Only two pieces of code from the previous pages have been modified: the iframe page, and the response handler. A look at the return page will help explain the changes to the function handleResponse.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Title</title> <script type="text/javascript"> function returnCall() { var handle = null; if (parent!=self) { if (this.frameElement) { handle = this.frameElement; } else if (parent.document.getElementById("iframe")) { handle = parent.document.getElementById("iframe"); } else { alert("Out of luck"); } if (handle) { handle.callBack('99.99');"; } } } window.onload = returnCall; </script> </head> <body> <div id="data-wrapper">nbsp;</div> </body> </html>
A PHP script calculates the answer and generates the page returned to the the iframe. The answer was returned as an argument to the function callBack. callBack is a method added to the iframe object during initalization. Its function is to populate three properties readyState, status (for IE), and responseText then call the onreadystatechange method. The function do_rpc assigned handleResponseMath (below) to the property onreadystatechange so it will run when called by callBack.
function handleResponseMath(){ if (HTTPObj.readyState == 4 || HTTPObj.readyState == "complete") { if (HTTPObj.status == 200) { var ans = HTTPObj.responseText; var id = (HTTPObj.targetId) ? HTTPObj.targetId : HTTPTarget; document.getElementById(id).value = ans; } else if (HTTPObj.readyState != "complete" { /* This branch is only valid when used with the XMLHttprequest * object. */ alert(HTTPObj.status + ": " + HTTPObj.status.Text); } } } //eof handleResponseMath
handleResponse: In this demonstration, handleResponseMath, simply assigns the value of HTTPObj.responseText to the field specified in HTTPObj.targetId. HTTPObj.targetId was set by do_rpc. The two conditions for the if statements are for compatibility with the xmlHttpRequest object. The properties are set by callBack when the iframe's onload event fires so they evaluate as true.
There can be conflicts with frames (like this site) in IE 5.5 and IE 6 see Journal entry 2/8/2006