Transporting Chunks of Text to the Server

| No Comments

I've jumped on the XMLHTTPRequest bandwagon. On some potentially large forms, I'm POSTing answers to individual questions as they are completed. The answers are packaged as small packets of XML.

Creating the XML packets is a two-step process. First, create an XML element.

    if (typeof ActiveXObject != 'undefined') {
        xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
        myElem = xmlDoc.createNode(1, 'FOOTAG', '');
        xmlDoc.appendChild(answerElem);
    } else {
        myElem = document.createElement('FOOTAG');
    }
    myElem.setAttribute('foo', bar);
    myElem.setAttribute('foo2', bar2);

Once all the attributes have been set, I need the element as a string before I can send it.

function serializeElement(elem)
{
    var serialized;
    try {
        // XMLSerializer exists in current Mozilla browsers
        serializer = new XMLSerializer();
        serialized = serializer.serializeToString(elem);
    } catch (e) {
        // Internet Explorer has a different approach to serializing XML
        serialized = elem.xml;
    }
    return serialized;
}

This handles the main browsers I care about: Mozilla Firefox and Internet Explorer (the current versions). From here I just use the XMLHTTPRequest object as documented in a hundred million places by now.

One more small wrinkle. The server software loses line breaks when parsing XML. In order to get around the problem, I decided to encode multi-line answers before sending. Base64 encoding is supported by the Mozilla browsers but not IE (and it's bulky and not human-readable). Strangely enough, I opted for URL encoding. Initially, I was using JavaScript's escape() function. Then I found it put ugly %Uxxxx entities into its output that made the server software choke. A quick search turned up the solution: better to use encodeURI().

About this Entry

This page contains a single entry by Christian published on April 20, 2005 9:52 AM.

Example of arraycopy() usage was the previous entry in this blog.

Tiny Patch for Text::CSV is the next entry in this blog.

Find recent content on the main index or look in the archive to find all content.