Hey, this AJAX thing is pretty easy, after all
Today, for the first time, I added AJAX (aka XMLHttpRequest) to a web application. (Well, it wasn’t actually AJAX, because I was making a synchronous request instead of an asynchronous one, but close enough.) I’ve known about the technique for just slightly longer than it has been dubbed “AJAX”, but never taken the time to figure out how to use it. Now that I know how to use it, I wish I had known about it years ago. This whole time (the 6 or so years I’ve been doing serious web development), I’ve been limping along with hacky solutions like refreshing an invisible frame, polling the server. Yuck. This makes so much more sense.
To make things somewhat easier for myself, I created a reusable javascript function to wrap the details of the XML call:
/*
Sends a POST request to the server in the background and
returns the result as XML or false if there was a problem
sending the request.
*/
function synchronousPost(requestURL, parameterMap) {
var requestBody = "";
for (param in parameterMap) {
if (requestBody != "") {
requestBody += "&";
}
requestBody += param + "=" + parameterMap[param];
}
var xmlRequest;
if (window.XMLHttpRequest) {
xmlRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlRequest) {
xmlRequest.open("POST", requestURL, false);
xmlRequest.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded");
xmlRequest.send(requestBody);
if (xmlRequest.status == 200) {
return xmlRequest.responseXML;
}
}
return false;
}
Then in my java Struts action class on the server side, I just need to make sure to set the content type, write my xml directly out to the response, and return null for the ActionForward:
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
String xml = "<response>";
xml += "success";
xml += "</response>";
response.setContentType("text/xml");
response.getWriter().write(xml);
return null;
}
Of course, you don’t need to use a Struts action class for this, but since all my code uses Struts, it’s easiest just to use the same framework.
I was pretty excited to get this to work - it’s a neat little technology, and it solved a little UI issue I was running into.
August 1st, 2005 at 11:20 am
I need to brush up on this, cuz I don’t comprehend HALF of what you’re explaining here…
I guess I’ll start here, and move forward. Then, I’ll come back here and see if understand more…
August 1st, 2005 at 12:08 pm
Just looked at that article, and it looks very good and thorough.
Sorry for being incomprehensible.
The above post is not so much an explanation of AJAX as it is an example of how I’ve put it to use in my own code.
August 8th, 2005 at 12:42 pm
Hey Jennifer.
Quick sidenote: I’m not sure what means you are using to format your code in your blog, but I’ve downloaded several code formatters for WordPress and very much like this one (Code Snippet).
It has support for 35 different languages, it color codes, creates hyperlinks to online language API’s, and is all-around nifty.
Plus, the person who develops it is very friendly. I reported a small bug to him and he had a new version out within hours.
August 8th, 2005 at 12:52 pm
Hey Steve, thanks for the link - I’ll definitely try out that plugin.
The code above is just wrapped in pre tags, nothing fancy.
January 4th, 2006 at 11:10 am
First of very useful code. I am just beginning using ajax along with the struts and your code has been some of the most beneficial. I do have one question. My experience is primarily on the back end so I am curious what the corresponding HTML looks like that calls ’synchronousPost’. Is this a map such as java uses and if so how do you create that in html.
Thank you
Shawn
January 4th, 2006 at 11:51 am
Hi Shawn, glad to be of help!
To use synchronousPost, you would create an array in javascript. So, for example, you might have this javascript function in your HTML:
<script type="text/javascript"> function helloWorld() { var parameterMap = new Array(); parameterMap["name"] = "Jennifer"; var result = synchronousPost("helloWorld.do", parameterMap); if (result) { var output = result.getElementsByTagName("output")[0].childNodes[0].nodeValue; alert(output); } else { alert("There was a problem sending the request to the server"); } } </script>Then somewhere in your HTML, you could call this function:
You can see that parsing the result gets a little tricky and verbose with the DOM scripting, but you could also just return a snippet of text or HTML instead of XML, and use the javascript innerHTML property or document.write() method to add the result to your document.
January 5th, 2006 at 10:12 am
This is the part I didn’t know you could do:
parameterMap[”name”] = “Jennifer”;
Thank you.
Shawn