Home Made Javascript MVC Explained Part 2

Created: 23 September 2020  Modified:

In part two of this series we will look into retrieving JSON data. In part one, we hard coded our JSON data into our Javascript. Normally we would retrieve our JSON data from a web service. Pulling the data from a service has security concerns. Cross Site Request Forgery (CSRF), JSON Hijacking and Javascript Hijacking are three of the security concerns. A static JSON file has been published to this site which will mimic providing data from a web service.

For part two I have created a working example. This allowed us to make a simpler example by not having to deal with Cross-Origin Resource Sharing (CORS). For the same reason we also use JQuery to handle our AJAX calls. We will break down the example and explain its parts. Starting with the core of this example. The runURL function take four parameters. The URL we are trying to call. The data we want to send to the URL. A reference to a function we want to run if accessing the URL is successful. Lastly a reference to a function we want to run if it fails.

The first four lines of the runURL function define a JSON object containing a token and time. In our example these are for illustration purposes only. The token and/or time would be checked server side to validate the request. The following line combines the requestData and data objects. The final three lines make an AJAX request. If the request is successful, the successCallback function will be run. If not the failCallback function will be run.

runURL

<html>
    <head>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"
        integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
        crossorigin="anonymous">
    </script>
    <script>
        function runURL (url, requestData, successCallback, failCallback) {
            var data = {
                'p_auth' : 'secretToken',
                't' : new Date().getTime()
            }
	    $.extend(true, data, requestData);
            $.get(url, data)
                .done(successCallback)
                .fail(failCallback);
        }       
    </script>
</head>
  <body>
  </body>
</html>

The next function we will look into is getSafeJSON. The parameter will be a string representing a JSON object. Server side we will have prefixed our JSON string with “while(1);”. This helps combat JSON Hijacking. To use our JSON string we must first remove this prefix. In the second line we use JQuery to parse the string and convert to an object.

getSafeJSON

        function getSafeJSON(jsonData) {
          var safeJSON = jsonData.replace("while(1);", '');
          var safeJSONObj = $.parseJSON(safeJSON);
          return safeJSONObj;
        }	

Next we need to define a method we want to run if our URL request is successful and one if it is not. These functions write information to the page indicating they have been run. We define the requestJSON to represent unique information that would represent a record. It is present to mimic real world code. We follow this by defining two URL strings. One is valid and the other is not. Finally we execute our runURL function with the valid and invalid URLs.

Define our functions and execute

        function success(data) {
           var safeJSONData = getSafeJSON(data)
           document.getElementById("successText").innerHTML = JSON.stringify(safeJSONData);
        }

        function fail(jqXHR, textStatus, errorThrown) {
           document.getElementById("failText").innerHTML = this.url;
        }

        
        var requestJSON = {
            'uniqueIdentifier' : 1
        }

        var url = "https://codeexcursion.com/2020/home-made-javascript-mvc-explained-part-2.txt";
        var badURL = "https://codeexcursion.com/2020/not-there.txt";

        runURL(url, requestJSON, success, fail);
        runURL(badURL, requestJSON, success, fail);

Below is the entirety of our example code. Note the div tags that will be modified by the success and fail functions.

Complete example

<html>
    <head>
        <meta http-equiv="Access-Control-Allow-Origin" content="*">
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"
            integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
            crossorigin="anonymous">
    </script>
    <script>
        function runURL (url, requestData, successCallback, failCallback) {
            var data = {
                'p_auth' : 'secretToken',
                't' : new Date().getTime()
            }
	    $.extend(true, data, requestData);
            $.get(url, data)
                .done(successCallback)
                .fail(failCallback);
        }   
        
        function getSafeJSON(jsonData) {
          var safeJSON = jsonData.replace("while(1);", '');
          var safeJSONObj = $.parseJSON(safeJSON);
          return safeJSONObj;deleteme.html
        }        

        function success(data) {
           var safeJSONData = getSafeJSON(data)
           document.getElementById("successText").innerHTML = JSON.stringify(safeJSONData);
        }

        function fail(jqXHR, textStatus, errorThrown) {
           document.getElementById("failText").innerHTML = this.url;
        }

        
        var requestJSON = {
            'uniqueIdentifier' : 1
        }

        var url = "/assets/2020/home-made-javascript-mvc-explained-part-2.txt";
        var badURL = "/assets/2020/not-there.txt";

        runURL(url, requestJSON, success, fail);
        runURL(badURL, requestJSON, success, fail);
    </script>
</head>
  <body>
      <div>
      Example HTML page demonstrating using JSON.  View the source for more detail.
      </div>
      <br/><br/>
      This is the result of a success.
      <div id="successText">
      
      </div>
      <br/><br/>
      This is the result of the fail.
      <div id="failText">
      
      </div>
      
  </body>
</html>
tags: ecmascript - javascript - mvc - html - json
   Less Is More