Thursday, May 26, 2016

JS Series: JavaScript xmlHttp GET Request


In this post I will provide a code sample for how to do simple xmlHttp GET requests and update a unordered list of times to display great nerdy Chuck Norris quotes using the icndb (Internet Chuck Norris Database).

In order to keep things simple at the beginning I'm going to try write all my JavaScript in the same html file. Once we move to modules and server side I'm sure that won't be possible but for now let's keep things simple. 


1. Create a new file called index.html and paste the following code into the file and save.

<script>
    function httpGetAsync() {  
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            callback(xmlHttp.responseText);
        }
    }
    xmlHttp.open("GET", "http://api.icndb.com/jokes/random", true); // true for asynchronous 
    xmlHttp.send(null);
}

function callback(respString) {
            var joke = getJoke(respString);
            var quoteList = document.getElementById("quoteList");
            var li = document.createElement("li");
            li.appendChild(document.createTextNode(joke));
            quoteList.appendChild(li);
}

function getJoke(respString) {
    var obj = JSON.parse(respString);
    return obj.value.joke;
}

</script>
<input type="button" value="Get Quote" onclick="httpGetAsync()" />
<ul id="quoteList"></ul>

2. Open The File With Your Browser

Locate the new index.html file you just created and double click on it. This should open the file along with the script code into your browser. You should be supplied with a single button with a label called "Get Quote". Clicking on this button will fire off an asynchronous get request to the incdb server and return a string of data (JSON format) which we will show in the browser.




ScreenShot



Items To Note

  • There was a button added to the page which called the httpGetAsync() JS function.
  • The httpGetAsync method created a new xmlHttp object and opened a GET connection to a specific URL and called send.
  • The xmlHttp object created has a callback function assigned when the state of the connection changed.
  • This change fired off a call to a new method aptly named callback which took the response json returned. 
  • The response json (JavaScript Object Notation) was then created using the JSON.parse method which takes a regular string and creates the actual JSON object.
  • This method also accesses the joke object value and returns it to the calling function.
  • Next the callback finds the UL tag by id, creates a new LI element, appends the joke text into that LI tag, then appends that LI back into the UL tag so the list continues to grow each time you hit the Get Quote button.

I hope you enjoyed this simple yet powerful example of how to do a GET with JavaScript. As I continue down this path I look forward to the many challenges I will face. I can already tell just how powerful this whole JS thing is nowadays with this simple script. 

Enjoy!


No comments:

Post a Comment