JQuery vs. custom JS AJAX

I’d like to share my experience using custom Javascript library and JQuery for AJAX work. Also, I used gson to make JSON object from the collection. gson makes object conversion really easy. All sample codes below are not complete one. Just wanted to show you an idea of how things are working.

AJAX Javascript

  • Import Javascript in all JSP where Ajax action is happening.
  • Handling different browsers logic needs to be coded.
  • Conversion to JSON and object parse need to be coded.
/*
 * Create tye most optimal XML HTTP request
 * object for the browser.
 */
function createRequest()
{
    var v;

    try
    {
        v = new XMLHttpRequest(); //Mozilla and IE7
    }
    catch ( e )
    {
        v = createActivexXMLHttp(); //IE6 and back
    }

    if ( v == null )
        throw new Error("XMLHttpRequest not supported");

    return v;
}

function createActivexXMLHttp()
{
    var aVersions = [ "MSXML2.XMLHttp.5.0",
        "MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
        "MSXML2.XMLHttp","Microsoft.XMLHttp"];

    for ( var i = 0; i  0 )
        {
            body = body + "&";
        }
        body = body + escape(name) + "=" + escape(requestData[name]);
    }
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type",
            "application/x-www-form-urlencoded; charset=UTF-8");
//    logger.trace("Post body:" + body);
    xhr.send(body);
}
/*
 * Converts a DOM document into XML text in a browser
 * neutral fashion.
 */
function getXMLString( doc )
{
    var xml = null;
    try
    {
        //Mozilla
        var ser = new XMLSerializer();
        xml = ser.serializeToString(doc);
    }
    catch ( e )
    {
        //IE
        xml = doc.xml;
    }

    return xml;
}

/*
 * Utility method that posts a DOM document.
 */
function ajaxPostDocument( url, doc, onLoad, data )
{
    var xhr = createRequest();

    xhr.onreadystatechange = function()
    {
        if ( xhr.readyState == 4 )
        {
            if ( xhr.status == 200 )
            {
                onLoad(xhr, data);
            }
            xhr = null; //Prevent memory leak in IE
        }
    }
    var xml = getXMLString(doc);
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type",
            "application/x-www-form-urlencoded; charset=UTF-8");
    xhr.send("xml=" + escape(xml));
}

ajaxPost() function was used from JSP to call Ajax request.

Object to JSON without gson

JSONArray was used to convert objects into JSON. Also JSONWritter was used to pass other parameters from server to client.

StringWriter aWriter = new StringWriter();
JSONWriter theWriter = new JSONWriter( aWriter );
JSONArray jsonArray = new JSONArray();
JSONObject object = new JSONObject(ajaxBean, PROPERTY_LIST); 
//Simple javabean with properties and String array with properties
jsonArray.put(object);

theWriter.object().
        key( "outages" ).value( jsonArray ).        
        key( "successfulIndicator" ).value( "1" ).        
        key( "error" ).value( "" ).
        endObject();
aWriter.toString();

Parse in JSP

function displayGrid( reply )
{
  var jsonString = reply.responseText;

  if ( jsonString != null && jsonString != "" )
  {
    var tableData = eval("(" + jsonString + ")");
    if ( tableData.error != "" )
    {
      $("#error").text(tableData.error);
    }
    else
    {
      $("#error").empty();
      var outageList = tableData.outages;
      for ( var i = 0; i < outageList.length; ++i )
      {
            var outage = outageList[i];
            var cell = row.insertCell(0);
            cell.innerHTML = outage.id;
            ....
      }
    }
  }
}

Lots of JS code…

AJAX JQuery using gson

public void doPost( HttpServletRequest aRequest, HttpServletResponse aResponse )
{
   Collection lockList 
   = convertToAjaxBean(getService().getWorkProtectionJobController().retrieveAllDataLock());

   Gson gson = new Gson();
   String json = gson.toJson( lockList );
   aResponse.setContentType( "application/json" );
   aResponse.getWriter().write( output );
}

Parse JSON from JSP

function retrieveAll()
  {
    $.ajax({
      url: servletUrl,
      dataType: 'json',
      data: {Action : "retrieveAll"},
      cache: false,
      beforeSend: function()
      {
        messageBox_show();
      },
      success: function(data)
      {
        drawTable(data);
      },
      complete: function()
      {
        messageBox_hide();
      }
    });
  }

  function drawTable(data)
  {
    var table = document.getElementById("ajaxTable");
    for(var i = 0; i < data.length; i++)
    {
      var lock = data[i];
      var rowIdx = table.rows.length;
      var row = table.insertRow(rowIdx);

      var cell = row.insertCell(0);
      cell.align = "left";
      cell.className = "tips";
      cell.innerHTML = lock.objectId;
      ....
    }
}

Because JSON is not nested with another array, I could just access JSON data from JQuery ajax call on Success.

Conclusion

JQuery and gson combination makes development a lot easier.  Although some shorthanded JQuery usage is really tricky, but once I master the actual JQuery Ajax syntax, it doesn’t seem too bad to understand shorthanded format. Some situation, returned JSON object contains complex structure such as nested JSON array. I found printing out JSON and validate its format through JSONLint before parsing JSON is helpful.

Advertisements

One thought on “JQuery vs. custom JS AJAX

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s