XMLHttpRequest Explained

Leave a comment

The XMLHttpRequest is an API used in modern web browsers. It contains methods that allow communication between the web browser and a web server through JavaScript. Although the name is XML, it can also support JSON.

Let’s go through an example of how to use it.

First, we will use a previous example where we have a WCF web service set up. This service is then uploaded to Azure so it can be accessed.

Next, create an HTML page with the following JavaScript:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title></title>
 <script type="text/javascript" >
 var request = null;
 if (window.XMLHttpRequest)
 {
 request = new XMLHttpRequest();
 }
 else if (window.ActiveXObject)
 {
 request = new ActiveXObject("Microsoft.XMLHTTP");
 }
 
 request.open ('POST', 'http://webserviceurl/Service1.svc', true);
 request.setRequestHeader('SOAPAction', 'http://tempuri.org/IService1/DoWork');
 request.setRequestHeader('Content-Type', 'text/xml');
 var data = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
 data += ' <soap:Body>';
 data += ' <DoWork xmlns="http://tempuri.org/" />';
 data += ' </soap:Body>';
 data += '</soap:Envelope>';
 request.onreadystatechange = function ( )
 {
 if(request.readyState == 4)
 {
 var response = request.responseXML;
 var DoWorkResult= response.getElementsByTagName("DoWorkResult")[0]; 
 alert(DoWorkResult.textContent);
 }
 };
 request.send(data);

 
 </script>
</head>
<body>
 
</body>
</html>

When the code runs, it will instantiate an object of XmlHttpRequest. The object will then post to the web service a SOAP envelope to the DoWork method. DoWorkRequest is returned from the web service. When we run the code, an alert box will display Hello World:

Note the tool http://webservicestudio.codeplex.com/releases/view/13915 is useful for determining the format of the SOAP requests.

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

Leave a Reply

Your email address will not be published. Required fields are marked *