Making A Cross-Domain Request with CORS and XML

October 9, 2017 Maria C. Lima

Below is the code to make a cross-domain request with CORS and XML using HTML, CSS, and JavaScript. Please contact me at maria@mclinteractive.com if you have any questions. I also wrote the code for a cross-domain request with CORS and JSON.

Demo

Order Details

Order No. Order date Title Quantity Total

Resources

Description

Making a CORS, which stands for Cross-Origin Resource Sharing, request allows cross-domain communication from the browser. This is an example of making a cross domain request based on Monsur Hossain’s article.

XML

Here is the xml feed:

<?xml version="1.0" encoding="UTF-8"?>
<xmlOrders>
  <shipto>
    <name>Jane Doe</name>
    <address>253 Dale St., Apt. 15</address>
    <city>Saint Paul</city>
    <state>MN</state>
    <zip>55103</zip>
  </shipto>
  <item>
    <number>304058674035</number>
    <date>01-13-2017</date>
    <title>DAGGER WITH SCABBARD</title>
    <note></note>
    <quantity>1</quantity>
    <total>42.99</total>
  </item>
  <item>
    <number>103504027396</number>
    <date>02-09-2017</date>
    <title>DISCOVER</title>
    <note></note>
    <quantity>1</quantity>
    <total>14.96</total>
  </item>
  <item>
    <number>304055403758</number>
    <date>03-08-2017</date>
    <title>BUTTER TOFFEE CASHEWS</title>
    <note></note>
    <quantity>1</quantity>
    <total>23.65</total>
  </item>
  <item>
    <number>304054144406</number>
    <date>04-07-2017</date>
    <title>FIGI'S CASHEWS</title>
    <note></note>
    <quantity>1</quantity>
    <total>44.07</total>
  </item>
  <item>
    <number>304059825304</number>
    <date>04-14-2017</date>
    <title>100 YRS AMERICAN QUARTERS</title>
    <note></note>
    <quantity>1</quantity>
    <total>30.08</total>
  </item>
  <item>
    <number>500673235029</number>
    <date>09-02-2017</date>
    <title>SEAT SILVER</title>
    <note></note>
    <quantity>1</quantity>
    <total>56.18</total>
  </item>
</xmlOrders>

JavaScript

Place the JavaScript before </body>.

<script>
(function(window, document, undefined){
    xmlOrders = {

        init: function(){
            var self = this;
            self.getData();
        },
        getData: function(){
            var self = this,
                url = "xmlOrders.xml";

            var createCORSRequest = function(method, url) {
                var xhr = new XMLHttpRequest();
                if ("withCredentials" in xhr) {

                    // Check if the XMLHttpRequest object has a "withCredentials" property.
                    // "withCredentials" only exists on XMLHTTPRequest2 objects.
                    xhr.open(method, url, true);

                } else if (typeof XDomainRequest != "undefined") {

                    // Otherwise, check if XDomainRequest.
                    // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
                    xhr = new XDomainRequest();
                    xhr.open(method, url);

                } else {

                    // Otherwise, CORS is not supported by the browser.
                    xhr = null;

                }
                return xhr;
                }

                var xhr = createCORSRequest('GET', url);
                if (!xhr) {
                throw new Error('CORS not supported');
                }

                xhr.onload = function() {
                var xml = xhr.responseText,
                    parser = new DOMParser(),
                    xmlDoc = parser.parseFromString(xml,"text/xml");
        
                // process the response.
                self.setPayee( xmlDoc);
                self.setData( xmlDoc);
                xmlOrders.xmlDoc = xmlDoc;
                
                };

                xhr.onerror = function() {
                console.log('There was an error!');
                };

                xhr.send();        
  
        },
        emptyTable: function(){
           var tbdy = document.getElementsByTagName('tbody')[0];
           tbdy.innerHTML = '';
        },
        setPayee: function(data){
            var self = this, data = data || xmlOrders.xmlDoc,
                dataObj = data.getElementsByTagName('shipto')[0];

                var name = dataObj.getElementsByTagName('name')[0].childNodes[0].nodeValue,
                    address = dataObj.getElementsByTagName('address')[0].childNodes[0].nodeValue,
                    city = dataObj.getElementsByTagName('city')[0].childNodes[0].nodeValue,
                    state = dataObj.getElementsByTagName('state')[0].childNodes[0].nodeValue,
                    zip = dataObj.getElementsByTagName('zip')[0].childNodes[0].nodeValue,
                    
                    pchId = document.getElementById('payee'),
                    para1 = document.createElement("p"),
                    para2 = document.createElement("p"),
                    para3 = document.createElement("p");
                    name = document.createTextNode(name);
                    address = document.createTextNode(address);
                    city = document.createTextNode(city + ', ' + state + ' ' + zip);
                    
                    pchId.className = 'payee';
                    para1.appendChild(name);
                    para2.appendChild(address);
                    para3.appendChild(city);
                    pchId.appendChild(para1);
                    pchId.appendChild(para2);
                    pchId.appendChild(para3);     


        },
        displayData: function(obj){

            var tbdy = document.getElementsByTagName('tbody')[0],

                row = tbdy.insertRow(0),

                number = row.insertCell(0),
                date = row.insertCell(1),
                title = row.insertCell(2),
                quantity = row.insertCell(3),
                total = row.insertCell(4);

                number.innerHTML = obj.getElementsByTagName('number')[0].childNodes[0].nodeValue;
                date.innerHTML = obj.getElementsByTagName('date')[0].childNodes[0].nodeValue;
                title.innerHTML = obj.getElementsByTagName('title')[0].childNodes[0].nodeValue;
                quantity.innerHTML = obj.getElementsByTagName('quantity')[0].childNodes[0].nodeValue;
                total.innerHTML = obj.getElementsByTagName('total')[0].childNodes[0].nodeValue;

        },
        setData: function(data){
            var self = this, data = data || xmlOrders.xmlDoc,
                dataObj = data.getElementsByTagName('item');

            self.emptyTable();

           for (var property in dataObj) {
                if (dataObj.hasOwnProperty(property)) {
                    self.displayData(dataObj[property]);
                }
            }
        },
        reverseData: function(){
            var self = this, data = xmlOrders.xmlDoc,
                dataObj = data.getElementsByTagName('item');
            
            self.emptyTable();

             function reverseObj(obj, fx) {
                var array = [];
                for (var key in obj) {
                     if (dataObj.hasOwnProperty(key)) {
                        array.push(key);
                     }                    
                }
                for (var i = array.length-1; i >= 0; i--) {
                    fx.call(obj, array[i]);
                }
            }

            reverseObj(dataObj, function(key){ self.displayData(this[key]); });
           
        }

    };
    
    
    (function(){
        xmlOrders.init();

        var button = document.getElementsByTagName('button')[0];

        button.onclick = function(){

             if (button.className !== 'reverse') {
                button.className = 'reverse';
                xmlOrders.reverseData();
            } else {
                button.className = '';
                xmlOrders.setData();
            }

        };
    }());

}(window, document));
</script>

HTML

Place the HTML somewhere in your page between the <body> and <\body>.

<header>
<h1>Current Order Details</h1>
</header>
<main>
	<div id="order-details">
		<div id="payee">
		</div>
		<button>Reverse Order</button>
		<table id="orderTable">
			<thead>
				<tr>
					<th>Order No.</th>
					<th>Order date</th>
					<th>Title</th>
					<th>Quantity</th>
					<th>Total</th>
				</tr>
			</thead>
			<tbody>
			</tbody>
		</table>
	</div>
</main>

CSS

Place the CSS somewhere between the <head> and <\head>.

<style>
#order-details button { 
    background-color:#d7d7d7;
    font-size:14px;
    padding:5px 10px;
	margin: 25px 15px;
    border-radius:5px;
    cursor:pointer;
 }
#order-details table {
    padding-top: 10px;
    background-color: #CC9;
    font-size: 0.8em;
	border-collapse: collapse;
	border-spacing: 0;
}
#order-details tr {  border: 1px solid #ccc; }
#order-details td, #order-details th {
   padding:15px;
    border: none;
    border-bottom: 1px solid #eee;
}
#order-details th {
	background-color: #9CC;
	font-weight:bold;
}
@media only screen and (max-width: 760px),
	(min-device-width: 768px) and (max-device-width: 1024px)  {

		#order-details table, #order-details thead, #order-details tbody, #order-details th, #order-details td, tr {
			display: block;
		}

		#order-details thead tr {
			position: absolute;
			top: -9999px;
			left: -9999px;
		}

		#order-details tr { border: 1px solid #ccc; }

		#order-details td {
			border: none;
			border-bottom: 1px solid #eee;
			position: relative;
			padding-left: 50%;
		}

		#order-details td:before {
			position: absolute;
			top: 6px;
			left: 6px;
			width: 45%;
			padding-right: 10px;
			white-space: nowrap;
		}

		#order-details td:nth-of-type(1):before { content: "Order No"; }
		#order-details td:nth-of-type(2):before { content: "Order Date"; }
		#order-details td:nth-of-type(3):before { content: "Title"; }
		#order-details td:nth-of-type(4):before { content: "Quantiy"; }
		#order-details td:nth-of-type(5):before { content: "Total"; }
	}           

</style>

, , , ,
Maria C. Lima

Maria C. Lima

Maria is an esteemed and celebrated independent web developer based in New York City. Her design and development work show tremendous passion and insight, which she brings to all of her clients and projects with love, professionalism, and an esteemed work ethic admired by all who partner with Maria.