Computers And Industry

XmlHttpRequest Sample


This code shows a sample of how one can make a web request using the XMLHttpRequest object in javascript. To use this sample, you must create an HTML page containing a button which invokes the DoRequest function in the button onclick event. When the sample is run, it simply displays the returned xml in an alert dialog window.

Using the Class


// define global variable
var rq = null;


// -------------------------------
// Do The Web Request
// -------------------------------
function DoRequest()
{

    // get a new request
    var rq = new pfsRq();

    // set the url
    rq.url = "http://whois.arin.net/rest/org/ARIN/pocs";

    rq.ahdr("Accept", "text/xml");

    // set the return handler
    rq.responseHandler = DoRequestResponseHandler;

    rq.get();
}


// -------------------------------
// Handle the Web Request Response
// -------------------------------
function DoRequestResponseHandler(rqst)
{

    if (!rqst.error)
    {
        alert(rqst.xtext);
    }

    // dispose
    rq = null;

}




The pfsRq class

The pfsRq class performs all the logic necessary to make a web request to any web service that returns xml, text, or html. However, it does not support binary data.


// **************************************************************
// PfsRq is a class that handles an get post request
// **************************************************************
function pfsRq()
{
  var MG = "GET";
  var MP = "POST";
  var MX = "POSTX";
  var ERR = "ERROR";

  this.id = -1;


  // flag indicating whether response is ready or not.
  this.ready = false;

  // error flag
  this.error = false;

    // error flag for xml document
  this.errorxd = false;

  // response code
  this.code = 0;

   // response message
  this.msg = "";

  // The http object
  this.h = null;

  // site name
  this.site = "";

  // method i.e. controller/action
  this.method = "";

  // time out in seconds
  this.timeout = 0;

  // response document
  this.xd = null;

   // response text
  this.xtext = "";

  // the url to call.
  this.url = "";

  // request user id
  this.uid = "";

  // request password
  this.pwd = "";

  // xml for post
  this.postxml = "";

  // post xmd document
  this.postxd = null;

  // post data already preset
  this.postdata = "";

   // form data object.
  this.formDataObject = null;

  // function to call after response
  // received
  this.responseHandler = null;

  // timeout function to call
  // if timeout occurs
  this.timeoutHandler = null;

  // error function to call
  // if error
  this.errorHandler = null;

  // query parameter array
  this.p = new Array();

  // header parameters
  this.hdr = new Array();

  // passthru values which are
  // available to response, error,
  // or timeout functions
  this.passthru = new Array();

  // back reference to self so
  // this object can be referenced
  // by handler functions
  var self = this;


  // ------------------------------------------------
  // name value pair
  // ------------------------------------------------
  this.nvp = function()
  {
    this.n;
    this.p;
  }

  // --------------------------------
  // Gets a new request object.
  // Returns null if unable to.
  // --------------------------------
  this.gnh = function()
  {
    var rslt = null;

    if (window.XMLHttpRequest)
    {
      rslt = new window.XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
      rslt = new window.ActiveXObject("Msxml2.XMLHTTP");
    }
    else if (window.ActiveXObject)
    {
      try
      {
        rslt = new window.ActiveXObject("Msxml2.XMLHTTP");
        }
      catch (e)
      {
        try
        {
          rslt =  new window.ActiveXObject("Microsoft.XMLHTTP");
        }

        catch (e) { }
      }
    }

    return rslt;
  }



  // ---------------------------------------------
  // ap adds a name value parameter
  // ---------------------------------------------
  this.ap = function(n,v)
  {
    var l = this.p.length;
    this.p[l] = new this.nvp();
    this.p[l].n = n;
    this.p[l].v = v;
  }

  // --------------------------------------------
  // adds a request header
  // --------------------------------------------
  this.ahdr = function(n,v)
  {
    var l = this.hdr.length;
    this.hdr[l] = new this.nvp();
    this.hdr[l].n = n;
    this.hdr[l].v = v;
  }


  // -------------------------------------------------------
  // this function receives the xml response
  // -------------------------------------------------------
  this.rh = function()
  {

    if (self.h.readyState == 4) {

      if (self.h.status == 200) {

          self.code = self.h.status;
          self.error = false;

        if (self.h.responseText)
        {
            self.xtext = self.h.responseText;


          if (self.h.responseXML)
          {
            self.xd = self.h.responseXML;
            self.errorxd = false;
          }


          // set the response handler.
          if (self.responseHandler != null)
          {
               self.responseHandler(self);
          }
        }

        // no response text received.  we have gotten a success though
        else
        {
            if (self.responseHandler != null)
            {
                self.responseHandler(self);
            }
        }

      } // end if status


      // status code 200 not received

      else
      {

        self.error = true;
        self.errorxd = true;
        self.code = self.h.status;
        try
        {
          self.msg = self.h.responseText;
        }
        catch(e)
        {
          self.msg = ERR;
        }

                // now return;
        if (self.errorHandler != null)
        {
            self.errorHandler(self);
        }
        else if (self.responseHandler != null)
        {
            self.responseHandler(self);
        }

      }

      // set the ready flag so that we can test it.
      self.ready = true;

    }

    return;

  }


  // ---------------------------------------------------------
  // Determines If Content Type header exists
  // ---------------------------------------------------------
  this.hdrExists = function(t)
  {
    var rslt = false;
    var t1 = t.toUpperCase();
    for (var i = 0; i < this.hdr.length; i++)
    {
      var n = this.hdr[i].n.toUpperCase();
      if (n == t1) {
        rslt = true;
        break;
      }
    }

    return rslt;
  }


  // --------------------------------------------------------
  // utility function to create url with parameters
  // --------------------------------------------------------
  this.mkurl = function(mode)
  {
      var tmp = this.url;
      var sep = "";

    if (tmp.length == 0) {

        tmp = "http://";


      if (this.site.length > 0) {
          tmp += sep + this.site;
          sep = "/";
      }
      if (this.method.length > 0) {
          tmp += sep + this.method;
          sep = "/";
      }


      if (mode == MG)
      {
        var tmpp = this.mkps();
        if (tmpp.length > 0) {
          tmp += "?" + tmpp;
        }
      }

    }

    return tmp;
  }


  // -----------------------------------
  // mkps makes a parameter string.
  // -----------------------------------
  this.mkps = function()
  {
    var s = "";
    var t = "";

    if (this.p.length > 0) {

      for (var i = 0; i < this.p.length; i++)
      {
        s += t + this.p[i].n + "=" + encodeURIComponent(this.p[i].v);
        t = "&";
      }

    }
    return s;
  }


  // -----------------------------------------------------------
  // clears the class properties
  // -----------------------------------------------------------
  this.clrsp = function()
  {
    this.error = false;     // error flag
    this.errorxd = false;   // error flag xdocument
    this.ready = false;     // clear the ready flag
    this.code = 0;          // response code
    this.msg = "";          // response message
    this.h = null;          // The http object
    this.xd = null;         // response document
    this.xtext = "";        // response text

  }

    // -------------------------------------------------------------
    // quality assures the async variable
    // -------------------------------------------------------------
  this.fixasync = function(async)
  {
    var rt = true;
    if (async != undefined)
    {
      if (async != null)
      {
          if (!async)
          {
              rt = false;
          }

        }
    }
    return rt;

  }


  // ------------------------------------------------------------
  // set request header.  Loop through hdr array and set the headers
  // accordingly
  // ------------------------------------------------------------
  this.sethdr = function()
  {
    for (var i = 0; i < this.hdr.length; i++)
    {
      this.h.setRequestHeader(this.hdr[i].n, this.hdr[i].v);
    }
  }

  // ------------------------------------------------------------
  // sets the content type for form post
  // ------------------------------------------------------------
  this.setct = function(s)
  {
     this.ahdr("Content-Type", "application/x-www-form-urlencoded");
  }



  // -----------------------------------------------------------
  // Get Function
  // -----------------------------------------------------------
  this.get = function(async)
  {

    async = this.fixasync(async);

    // clear the response;
    this.clrsp();

    //set error to true.
    this.error = true;
    this.errorxd = true;
    this.msg = ERR;

    // get a new http object
    this.h = this.gnh();



    // test if we actually got an http.
    if (this.h)
    {

      // set the new url.  Note, if the url property is already set,
      // then we totally ignore this.
      this.url = this.mkurl(MG);




      // if we are not doing synchronous (ie wait for), then
      // we need to set the on ready state change handler.  We
      // set it to the internal request handler
      if (async)
      {
          this.h.onreadystatechange = this.rh;
      }

      // set the timeout handler
      if (this.timeoutHandler != null)
      {
          this.h.ontimeout = this.timeoutHandler;
      }

      // now test the uid.  If not blank, then we are to use it.

      if (this.uid.length > 0) {
         this.h.open(MG, this.url, async, this.uid, this.pwd);
      }
      else {
         this.h.open(MG, this.url, async);
      }



      // if a timeout is set, then
      // set the http object timeout
      if (this.timeout > 0)
      {
          this.h.timwout = this.timeout * 1000;
      }


      // send the message
      this.h.send();


      // now if we are in synchronoous mode, then we got to wait
      // so we might as well set the response text

      if (!async) {

        try {

          // if we get anything, we set the error code
          // to false. i.e. we may be only getting
          // text...not an xml document
          if (this.h.responseText)
          {
            this.xtext = this.h.responseText;

            if (this.h.responseDocument) {

              this.xd = this.h.responseDocument;
            }

            this.error = false;
            this.code = this.h.status;
          }

        }
          catch (e)
          {
              if (this.errorHandler != null) {
                  this.errorHandler(self);
              }
          }

        // set the ready flag
        this.ready = true;

      } // end if not async mode, aka sync wait for

    } // end if http

  }



  // -------------------------------------
  // posts to a url
  // ------------------------------------

  this.post = function(async)
  {
    var pdata = "";

    async = this.fixasync(async);


    // clear the response;
    this.clrsp();

    //set error to true.
    this.error = true;
    this.errorxd = true;
    this.msg = ERR;

    // get a new http object
      this.h = this.gnh();



    // test if we actually got an http.
    if (this.h) {

      // set the new url.  Note, if the url property is already set,
      // then we totally ignore this.  Also note the MP value.  This signifies that it
      // it is a mode post.  Whether xml or post doesn't matter in this case so we will
      // just use mode post.
      this.url = this.mkurl(MP);

      // since this is a post, we need to construct some post data.  We use
      // a bit of logic here.  if the xml data is set, we will send that. Otherwise,
      // we'll look at the post data.  If that is set, then we will send that.  Otherwise,
      // we'll look to the p array for the parameter list.

      if (this.formDataObject == null) {

          if (this.postxml.length > 0) {
              pdata = this.postxml;
          }
          else if (this.postdata.length > 0) {
              pdata = this.postdata;
          }
          else {
              pdata = this.mkps();
          }


          // if the content header does not exist, then set the default
          if (!this.hdrExists("Content-Type"))
          {
              this.setct(pdata);
          }

      }



      // if we are not doing synchronous (ie wait for), then
      // we need to set the on ready state change handler.  We
      // set it to the internal request handler
      if (async)
      {
         this.h.onreadystatechange = this.rh;
      }

      // now test the user id.  if it is non blank, then 
      // we will call the web resource with a user id and 
      // and password.

      if (this.uid.length > 0) {
         this.h.open(MP, this.url, async, this.uid, this.pwd);
      }
      else {
         this.h.open(MP, this.url, async);
      }

      // set the request headers
      for (var i = 0; i < this.hdr.length; i++)
      {
          this.h.setRequestHeader(this.hdr[i].n, this.hdr[i].v);
      }


      // send the message along with the data.  if the form data object is
      // null, then
      if (this.formDataObject == null)
      {
          this.h.send(pdata);
      }
      else
      {
          this.h.send(this.formDataObject);
      }

      // now if we are in synchronoous mode, then we got to wait
      // so we might as well set the response text

      if (!async) {

        try {

          // if we get anything, we set the error code to false.
          // i.e. we may be only getting text...not an xml document
          if (this.h.responseText) {
            this.xtext = this.h.responseText;

            if (this.h.responseDocument) {

              this.xd = this.h.responseDocument;
            }

            this.error = false;
            this.code = this.h.status;
          }

        }
          catch (e)
          {
              if (this.errorHandler != null)
              {
                  this.errorHandler(self);
              }
          }


          // set the ready flag
        this.ready = true;



      } // end if not async mode, aka sync wait for

    } // end if http

  }




  // --------------------------------------------------------
  // postxml is a wrapper method which prepares xml data
  // to be sent to the server.  NOTE.  IF postxd is set, the
  // contents of the xml document will overwrite the postxml string
  // --------------------------------------------------------
  this.postTypeXml = function(async)
  {

    async = this.fixasync(async);

    if (this.postxd != null || this.postxml.length > 0)
    {

      // if the post xml document is not null, then
      // we need to transform it to xml

      if (this.postxd != null) {

        this.postxml = new XMLSerializer().serializeToString(this.postxd);
      }

      // now add the xml headers
      this.ahdr("Content-Type", "text/xml");
      this.ahdr("Accept", "text/xml");


      // call the main post
      this.post(async);

    }

  }



  // ---------------------------------------------------------
  // Adds a passthru variable
  // ---------------------------------------------------------
  this.addPassthru = function(v)
  {
      var nlen = this.passthru.length;
      this.passthru[nlen] = v;
  }



}   // END RQ
Open Source

Paul F. Sirpenski
Personal Open Source Directory Of Paul F. Sirpenski

ASP.NET Core
Open Source directory Of the Microsoft Asp.Net Core project.

Developed By Paul F. Sirpenski. Copyright 2022.