Tweets

Http Web Request Using Plain Javascript

2022-08-20 08:35 PM sirpenski
2022-08-20 08:35 PM
   
Copy   Embed   Share


This example shows how to make an http request using plain javascript. This code does not rely on any external javascript frameworks. It also only shows how to do an asynchronous get request. It is not to be thought of as production ready. When testing this example, put the JSRequest object in its own file and include it into an html page via the script tag.

The idea is to set the url, the response handler (ie a javascript function that is called when the response is received, and then call the Get function (ie method). When the call returns, one handles the response text (or response xml document) accordingly. The code is shown below.


// ---------------------------------------------------------------
// The JSRequest Object is used to do web request to an internet
// resource. It does not rely on any external frameworks.
// ---------------------------------------------------------------
function JSRequest()
{

	this.Error = true;                  // Default To True.
	this.Http = null;                   // Http object
	this.Url = "";                      // The Url to call.
	this.UserID = "";                   // User ID
	this.Password = "";                 // Password

	this.ResponseHandler = null;        // The Response Handler is the function that gets called on receipt
	this.TimeoutHandler = null;         // timeout handler;
	this.ErrorHandler = null;           // error handler (not timeout)
	this.TimeOut = 0;                   // specifiy timeout in milliseconds
	this.Passthru = new Array();        // pass thru values

	var self = this;                    // The back reference to this class

	this.ResponseText = null;           // Holds The Return Text.
	this.ResponseXmlDocument = null;    // Holds the Response XML
	this.ResponseReady = false;         // A Flag To Indicate Response is ready
	this.ResponseStatusCode = 500;      // Response Status Code


	// -----------------------------------------------------------
	// Get Function	- Asynchronous
	// -----------------------------------------------------------
	this.Get = function()
	{

		// set for convenience. we pass this to the http
		// open function.
		var async = true;

		// set the error to true.
		this.Error = true;

		// get a new http object
		this.Http = this.GetNewHttp();


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


			// Set The Http Response Handler To The LOCAL Response Handler.
			// The local response handler will call the user defined response handler or
			// the user defined error handler
			this.Http.onreadystatechange = this.LocalResponseHandler;

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

			// now test the userid.  If not blank, then we are to use it.
			if (this.UserID.length > 0) {

				this.Http.open("GET", this.Url, async, this.UserID, this.Password);

			}
			else {

			   this.Http.open("GET", this.Url, async);
			}

			// set the alternate timeout
			if (this.TimeOut > 0)
			{
				this.Http.timeout = this.TimeOut;
			}


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

		}	// end if http not null

	}



	// -------------------------------------------------------
	// Actually receive the response. Function will call either
	// the user defined response handler or the user defined error
	// handler
	// -------------------------------------------------------
	this.LocalResponseHandler = function()
	{

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

			// set the status code
			self.ResponseStatusCode = self.Http.status;

			// if the status code is OK or success...
			if (self.Http.status >= 200 && self.Http.status < 300) {

				// set the error to false
				self.Error = false;

				// if response text is received, then save it.
				if (self.Http.responseText)
				{

					// set the object level response text.
					// Yes, I know... Always save the text so you can do a console.log
					// Dev Pro Tip
					self.ResponseText = self.Http.responseText;

					// if the response is a xml document
					if (self.Http.responseXML)
					{
						self.ResponseXmlDocument = self.Http.responseXML;

					}


					// call the response handler. Note, we are passing the self object
					// so we have access to everything.
					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 is 200 OK!


			// status code 200 not received. process as error.

			else {


				// 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.ResponseReady = true;

		}

		return;

	}


	// -----------------------------------------------------
	// Gets A New Http object.
	// -----------------------------------------------------
	this.GetNewHttp = 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;
	}


}
     

Usage: The following is a simple html page with a button on it. When one clicks the button, the button click event is run which actually does the web call. A message window pops up with the contents.


<!DOCTYPE html>
<html lang="en">
<head>

	<!-- include the jsrequest object -->
  	<script type="text/javascript" src="https;//somedomain.com/jsrequest.js">


	<!-- included javascript to support the web page -->
	<script type="text/javascript">

	// request
	var rq = null;

	// response handler
	function OnResponseHandler(CompletedRequest)
	{
		alert(CompletedRequest.ResponseText);
		rq = null;
	}

	// On button click function
	function OnButtonClick()
	{

		rq = new JSRequest();
		rq.Url = "http://somedomain.com/somegetmethod";
		rq.ResponseHandler = OnResponseHandler;
		rq.Get();

		return true;

	}
	</script>
</head>

<body>
	<button onclick="OnButtonClick()">Click Me</button>
</body>
</html>



  

I hope you find it helpful.

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.