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.
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.
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
Below is the entirety of our example code. Note the div tags that will be modified by the success and fail functions.