XMLHttpRequest (Part 2)


Just a continuation of the last post.

This XMLHttpRequest implementation straightens things out a bit. And, yes, I am well aware that there are better ways to do null checking. But if I did everything for you, you’d never have to learn anything for yourself…

function isObject(obj)
{
  var bIsObject = false;
  
  if( obj )
  {
    bIsObject = ( typeof obj=='object' );
  }
  
  return bIsObject;
}

function getObjectProperty( obj, strPropName )
{
  var prop = null;
  
  if( isObject(obj) && strPropName )
  {
    if( obj.hasOwnProperty(strPropName) )
    {
      prop = obj[strPropName];
    }
  }
  
  return prop;
}

function doHttpRequest( strUrl, objParams )
{
  var xmlhttp = null;

  try
  {
    // for all modern browsers
    xmlhttp = new XMLHttpRequest();
  }
  catch(e1)
  {
    try
    {
      // for IE5 and IE6
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e2)
    {
      alert("XMLHttpRequest object could not be created...");
    }
  }
  
  if( !xmlhttp )
  {
    alert("XMLHttpRequest object could not be created...");
  }
  else
  {
    var objRequestData = getObjectProperty(objParams, 'objRequestData');
    var bDoPost = getObjectProperty(objParams, 'bDoPost');
    var funcCallback = getObjectProperty(objParams, 'funcCallback');
    var objCallbackParams = getObjectProperty(objParams, 'objCallbackParams');
    
    if( !strUrl )
    {
      alert('URL cannot be blank...');
    }
    else
    {
      var strRequestData = '';
      if( objRequestData )
      {
        for( var strKey in objRequestData )
        {
          var strValue = objRequestData[strKey];

          if( strRequestData.length>0 )
          {
            strRequest += "&";
          }

          strRequestData += encodeURIComponent(strKey) + "=" + encodeURIComponent(strValue);
        }
      }
      
      xmlhttp.onreadystatechange = function()
      {
        if(xmlhttp.readyState == 4)
        {
          if( xmlhttp.status!=200 )
          {
            alert("Error in HTTP Request...\n\nStatus: "+xmlhttp.status+"\n"+xmlhttp.statusText);
          }
          else
          {
            if(!objCallbackParams)
            {
              objCallbackParams = { 'xmlhttp':xmlhttp };
            }
            else
            {
              objCallbackParams.xmlhttp = xmlhttp;
            }
            
            if( funcCallback )
            {
              funcCallback(objCallbackParams);
            }
            else
            {
              alert('http request done...');
            }
          }
        }
      }
      
      if( bDoPost )
      {
        xmlhttp.open("POST", strUrl, true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send(strRequestData);
      }
      else
      {
        xmlhttp.open("GET", strUrl+"?"+strRequestData, true);
        xmlhttp.send(null);
      }
    }
  }
}

Leave a Reply