Welcome to our free Advanced JavaScript Programming tutorial. This tutorial is based on Webucator's Advanced JavaScript Programming course.
In this exercise, you will make an Ajax call to a cross-origin site which includes appropriate response headers to enable CORS.
Access-Control-Allow-Origin: *
header:
geonames
contains an array (n this case with a single element) which contains fields with information about the given country: countryName
, population
, etc.#countryabbr
input field: this is the two-character country abbreviation - "US" for the United States, "CN" for China, "DE" for Germany, etc.get
.JSON.parse(xmlhttp.responseText).geonames.length == 0
, then display an error message.<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>CORS - Geonames</title> <style> #responseContent { width:66%; padding:1% 2%; background-color:#ccc; margin-top:20px; } h2 { margin:0; padding:0; } </style> <script> window.onload = function() { var btn = document.getElementById('btn'); var responseContent = document.getElementById('responseContent'); btn.addEventListener('click', function(e) { responseContent.innerHTML = '<h2>Response Content</h2>'; var country = document.getElementById('countryabbr').value; var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", "http://api.geonames.org/countryInfoJSON?formatted=true&lang=en&country=" + country + "&username=webucator&style=full", true); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { var jsonResponse = JSON.parse(xmlhttp.responseText); if (jsonResponse.geonames.length > 0) { responseContent.innerHTML += '<p>'; responseContent.innerHTML += 'Name: ' + jsonResponse.geonames[0].countryName + '<br>'; responseContent.innerHTML += 'Currency Code: ' + jsonResponse.geonames[0].currencyCode + '<br>'; responseContent.innerHTML += 'Capital City: ' + jsonResponse.geonames[0].capital + '<br>'; responseContent.innerHTML += 'Population: ' + jsonResponse.geonames[0].population + '<br>'; responseContent.innerHTML += '</p>'; } else { responseContent.innerHTML += '<p><em>Country not found</em></p>'; } } else { alert("failed!"); } } } xmlhttp.send(null); }); }; </script> </head> <body> <input type="text" id="countryabbr" placeholder="US"> <button id="btn">Fetch Country Info</button> <br> <div id="responseContent"></div> </body> </html>
Our Ajax calls goes out to
where country
is the user-entered value from the text field.
We check that the country code we send along in our Ajax call results in a valid response; if so, then we append to the #responseContent
div
some information about the country. If the response is empty, then we display "Country not found".
This tutorial is based on Webucator's Advanced JavaScript Programming Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.