Making A Cross-Domain Request with CORS and JSON

October 9, 2017 Maria C. Lima

Below is the code to make a cross-domain request with CORS and JSON using HTML, CSS, and ES6 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 XML.

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.

JSON

Here is the JSON feed:

{
  "jsonOrders": {
    "shipto": {
      "name": "Jane Doe",
      "address": "253 Dale St., Apt. 15",
      "city": "Saint Paul",
      "state": "MN",
      "zip": "55103"
    },
    "item": [
      {
        "number": "304058674035",
        "date": "01-13-2017",
        "title": "DAGGER WITH SCABBARD",
        "quantity": "1",
        "total": "42.99"
      },
      {
        "number": "103504027396",
        "date": "02-09-2017",
        "title": "DISCOVER",
        "quantity": "1",
        "total": "14.96"
      },
      {
        "number": "304055403758",
        "date": "03-08-2017",
        "title": "BUTTER TOFFEE CASHEWS",
        "quantity": "1",
        "total": "23.65"
      },
      {
        "number": "304054144406",
        "date": "04-07-2017",
        "title": "FIGI'S CASHEWS",
        "quantity": "1",
        "total": "44.07"
      },
      {
        "number": "304059825304",
        "date": "04-14-2017",
        "title": "100 YRS AMERICAN QUARTERS",
        "quantity": "1",
        "total": "30.08"
      },
      {
        "number": "500673235029",
        "date": "09-02-2017",
        "title": "SEAT SILVER",
        "quantity": "1",
        "total": "56.18"
      }
    ]
  }
}

JavaScript

If you don’t use development tools such as Webpack, compile the ES6 Javascript displayed below with Babel, and place it above </body>.

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

        init(){
            let self = this;
            self.getData();
        },
        getData(){
            let self = this,
                url = "jsonOrders.json";

            let createCORSRequest = function(method, url) {
                let 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;
                }

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

                xhr.onload = function() {
                let jsonDoc = JSON.parse(xhr.responseText);

                // process the response.
                self.setPayee( jsonDoc);
                self.setData( jsonDoc);
                jsonOrders.jsonDoc = jsonDoc;
                
                };

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

                xhr.send();        
  
        },
        emptyTable(){
           let tbdy = document.getElementsByTagName('tbody')[0];
           tbdy.innerHTML = '';
        },
        setPayee(obj){
            let self = this, data = obj || jsonOrders.jsonDoc,
                dataObj = data.jsonOrders.shipto;

                let name = dataObj.name,
                    address = dataObj.address,
                    city = dataObj.city,
                    state = dataObj.state,
                    zip = dataObj.zip,
                    
                    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(obj){

            let 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.number;
                date.innerHTML = obj.date;
                title.innerHTML = obj.title;
                quantity.innerHTML = obj.quantity;
                total.innerHTML = obj.total;

        },
        setData(obj){
            let self = this, data = obj || jsonOrders.jsonDoc,
                dataObj = data.jsonOrders.item;

            self.emptyTable();

           for (let property in dataObj) {
                if (dataObj.hasOwnProperty(property)) {
                    self.displayData(dataObj[property]);
                }
            }
        },
        reverseData: function(){
            let self = this, data = jsonOrders.jsonDoc,
                dataObj = data.jsonOrders.item;
            
            self.emptyTable();

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

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

    };
    
    
    (function(){//dom ready
        jsonOrders.init();

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

        button.onclick = function(){

             if (button.className !== 'reverse') {
                button.className = 'reverse';
                jsonOrders.reverseData();
            } else {
                button.className = '';
                jsonOrders.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.