spacer
Web Development Tutorials AJAX Tutorials
 Developer Newsletter

Tutorials
AJAX
ASP
CGI & Perl
CSS
Flash
HTML
Illustrator
Java
JavaScript
Linux
MySQL
PHP
Photoshop
Python
Wireless
XML
Miscellaneous


Scripts Directory
AJAX Scripts
ASP Scripts
ASP.NET Scripts
CGI & Perl Scripts
Flash Scripts
Java Scripts
JavaScript Scripts
PHP Scripts
Python Scripts
Remotely Hosted Scripts
Tools & Utilities Scripts
XML Scripts

Web Hosting Directory
ASP.NET
Budget
Dedicated Servers
Ecommerce
Linux
Resellers
Shared
Small Business
Windows

Developer Manuals
Learn HTML
Learn PHP
Learn CSS
Learn AJAX
Learn JavaScript
Learn Pear
Free White Papers

Developer Resources
Developer Tools
Developer Content
Survey Software
Dedicated Servers




The obligatory 'My Ajax Tutorial' Post

By Chris Kasten
2007-12-13


AJAX Tutorial

I posted about my battle with trying out "Ajax". I learned some stuff. While there are tons of Ajax Primers out there, I figured I could have one too, since I didn't find one that would teach me quite what I wanted to do (granted, I'm *not* a Javascript expert).

Some context here. I consider myself a pretty decent coder. In one language or another I have over 20 years under my belt. (not that you'll guess that from the below samples!). But javascript is not a forte of mine, by any stretch of the mind. And this XMLHTTPRequest stuff is very new to me. But I like it!

Here's some silly/simple stuff that I cobbled together while I was doing some of my troubleshooting.


First off, I needed a simple little "client" page. All this page had was the bare minimum html and a form with one checkbox. I called this page xmlhttp_client.asp. Here's the form, with one wrinkle:

ASP:
  1. <form action="post" name="test">
  2. <input type="checkbox" name="chkTest" onclick="submitTest(event);" />
  3. <%
  4. httpSetting = request.ServerVariables("HTTPS")
  5. if httpSetting = "on" then
  6. httpPrefix = "https://"
  7. else
  8. httpPrefix = "http://"
  9. end if
  10. fullPathInfo = httpPrefix & request.ServerVariables("Server_Name") & Request.ServerVariables("Path_Info")
  11. pathInfo = mid(fullPathInfo, 1, (InStrRev(fullPathInfo, "/")))
  12. %>
  13. <input type="hidden" name="root" value="<%=pathInfo%>" />
  14. </form>

See the wrinkle? Yeah, that big chunk of vbscript embedded in there. Gotta make sure the url's match coming and going from the server so I just build it up, stuff it in a form field and grab it from the javascript routines before I make my call (you'll see that next). If your goal isn't to be able to run your stuff on any old server without touching code, you can leave all that ASP/vbscript gunk out, of course.

Note this line, it is where all the magic really starts:

HTML:
  1. <input type="checkbox" name="chkTest" onclick="submitTest(event);">

Click the box, fire SubmitTest(). What does SubmitTest() look like? Funny you should ask.

JavaScript:
  1. function submitTest(evt){
  2. var buff
  3. // process event here, handles both IE and Mozilla event models
  4. evt = (evt) ? evt : ((window.event) ? window.event : "")
  5. if (evt) {
  6. elem = (evt.target) ? evt.target : evt.srcElement;
  7. URLString = document.test.root.value + "xmlhttp.asp";
  8. //alert(URLString);
  9.  
  10. http.open("POST", URLString, true);
  11. http.onreadystatechange = processReqChange;
  12. http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  13. http.send("action=submitTest");
  14. }
  15. }

Remember that goofy ASP logic in the HTML? You can see it actually means something now -- here's where it gets used:

JavaScript:
  1. URLString = document.test.root.value + "xmlhttp.asp";

xmlhttp.asp is, of course, the name of the file that contains all the server processing logic. Now, I'm insulated against moving my code from one server to another. Presumably, I won't be renaming xmlhttp.asp, of course.

Thing is, that function isn't quite as clear as it could be. You see an object named "http" referenced frequently, but I haven't showed where it came from yet! Oops. Well, easily remedied... This next bit just lives in the same block as all the rest:

JavaScript:
  1. function getHTTPObject()
  2. {
  3. var xmlhttp;
  4. /*@cc_on
  5. @if (@_jscript_version>= 5)
  6. try {
  7. xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  8. } catch (e) {
  9. try {
  10. xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  11. } catch (E) {
  12. xmlhttp = false;
  13. }
  14. }
  15. @else
  16. xmlhttp = false;
  17. @end @*/
  18.  
  19. if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
  20. try {
  21. xmlhttp = new XMLHttpRequest();
  22. xmlhttp.overrideMimeType('text/xml');
  23. } catch (e) {
  24. xmlhttp = false;
  25. }
  26. }
  27. return xmlhttp;
  28. }
  29.  
  30. var http = getHTTPObject(); // We create the HTTP Object

That code was cheerfully lifted from about a dozen other tutorial pages. I like it and it seems to work well. It is the epitome of a "cut, paste and don't overthink it" piece of code.

Look back to the SubmitTest() function and the use of that http object:

JavaScript:
  1. ...
  2. http.open("POST", URLString, true);
  3. http.onreadystatechange = processReqChange;
  4. http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  5. http.send("action=submitTest");
  6. ...

I'm doing a POST, to URLString (my server stuff in xmlhttp.asp) and, by setting "true" I indicate that it will be an async call. Thus, the next line. It sets my "callback" function -- processReqChange() in this case.

Because I'm doing this as a POST, I need to set the content-type (which was my personal waterloo for a day...). And finally, send it with whatever I care to post. If there are multiple vars to post, just format as if they're in a querystring (this=that&foo=bar&do=doot).

If I was doing this as a sync call, it gets a bit simpler. Just toss all my logic after that send to catch the response. But suppose there's some network issues? Or [insert hand-waving here to explain why I want this to be async besides "because it is neat-o"!]?

Our callback function doesn't do much:

JavaScript:
  1. function processReqChange()
  2. {
  3. var response;
  4. var result;
  5.  
  6. // only if http shows "complete"
  7. if (http.readyState==4) {
  8. if (http.status==200) {
  9. //alert("success");
  10. response = http.responseXML.documentElement;
  11. result = response.getElementsByTagName('result')[0].firstChild.data;
  12. alert(result);
  13. }
  14. else {
  15. alert("Failed: " +http.status);
  16. }
  17. }
  18. }

Very light weight. Originally, it solely existed to pop an alert message so I knew I just got that far. In the real world, I actually fill a <div> tag set with some user feedback so that my user knows something happened. In this case though, I just wanted to throw an alert either with what my server function sent back or what the http error might be. What about this readyState thing? There are 4 values:

0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete

[source]
In this case (most?) we really aren't all that interested until it is complete... but our callback will get called on each (change it, put in some alerts and watch each one roll by = exercise for the reader).

And there's the client.

----------

What does the server stuff look like? I have that all in a file called xmlhttp.asp (such clever names, I know). For this sample/testing, all I wanted to do was hit a specific row in the database, retrieve the boolean value and flip it. True to False. False to True. Then I could not only check my http response, and the xml I returned, but also independently just query that database.

ASP:
  1. <!-- #include File="db.asp" -->
  2. <%
  3.  
  4. dim action, sSQL, rsRecord, responseString
  5.  
  6. 'Get query string variables
  7. action = request.querystring("action")
  8. if action = "" then action = request.Form("action")
  9.  
  10. Select Case action
  11.  
  12. Case "submitTest"
  13. set rsRecord = Server.CreateObject("ADODB.Recordset")
  14. sSQL = "SELECT * FROM PARTY_EXTENSION where PRTY_ID = 9999"
  15. rsRecord.Open sSQL,cnSM,1,3
  16. if rsRecord("extension_value") = "true" then
  17. rsRecord("extension_value") = "false"
  18. else
  19. rsRecord("extension_value") = "true"
  20. end if
  21. rsRecord.Update
  22. responseString = "<?xml version=""1.0"" encoding=""UTF-8"" ?><response><result>Updated "&rsRecord("extension_value")&"</result></response>"
  23. rsRecord.Close
  24.  
  25.  
  26. Case Else
  27. 'No action
  28. responseString = "<?xml version=""1.0"" encoding=""UTF-8"" ?><response><result>Error - No Such Action Exists-"&action&"</result></response>"
  29. End Select
  30.  
  31. Response.ContentType ="text/xml"
  32. response.Write responseString

Nothing too fancy. Again, I just wanted to make sure the server was doing something and that I could independently verify it.



Tutorial Pages:
» AJAX Tutorial
» Summary


 | Bookmark Print |   Write For Us
Related Tutorials:
» Getting Started with AJAX in jQuery
» GWT Basics: AJAX Programming with Java
» AJAX Accessibility for Websites
» AJAX and PHP Form Processing
» A Designer's Guide to Prototyping Ajax
» Ajax Wireframing Approaches



About the NetVisits, Inc Network | Write For Us | Advertise
Copyright ©2007 NetVisits, Inc Network. All Rights Reserved. Privacy Policy.
Visit other NetVisits, Inc. sites: