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.

6 Responses to “Hey, this AJAX thing is pretty easy, after all”

  1. Matthom Says:

    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… :)

  2. Jennifer Says:

    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.

  3. Steve Eady Says:

    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.

  4. Jennifer Says:

    Hey Steve, thanks for the link - I’ll definitely try out that plugin.

    The code above is just wrapped in pre tags, nothing fancy.

  5. Shawn Says:

    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

  6. Shawn Says:

    This is the part I didn’t know you could do:
    parameterMap[”name”] = “Jennifer”;

    Thank you.
    Shawn