Retrieving XML with AJAX

Here we will make use of the AJAX methodology to retrieve details about your current location and IP address in XML format from http://ip-api.com/xml/. The XML response has the following structure.

				
					<query>
						<status>success</status>
						<country>United States</country>
						<countryCode>US</countryCode>
						<region>VA</region>
						<regionName>Virginia</regionName>
						<city>Ashburn</city>
						<zip>20149</zip>
						<lat>39.0438</lat>
						<lon>-77.4874</lon>
						<timezone>America/New_York</timezone>
						<isp>Amazon Technologies Inc.</isp>
						<org>Amazon Data Services NoVa</org>
						<as>AS14618 Amazon.com, Inc.</as>
						<query>3.88.25.171</query>
					</query>
				
			

An instance xhr of the XMLHttpRequest object is first created and its open method is initialized by passing the arguments GET (request), http://ip-api.com/xml/ (url) and true (asynchronous). The various states of the request can be monitored via the readyState property (in integer values from 0 to 4), on change of which the onreadystatechange event handler is triggered. The request operation is complete when the value of readyState equals 4. The other property to be considered is the status property which returns the HTTP response codes. A request is successful if the value is 200.

The response XML data from the server is contained in the responseXML property, with query as its root element. We select this root element using getElementsByTagName("query")[0].

Finally, request to the server is completed by invoking the send method. Wrapping it all in a self-invoking function, it becomes

				
				(function(){
					var xhr = new XMLHttpRequest();
					xhr.open("GET", "http://ip-api.com/xml/", true);					
				    xhr.onreadystatechange = function() {
				        if(xhr.readyState == 4 && xhr.status == 200) {
						    var geo = xhr.responseXML;
							var g = geo.getElementsByTagName("query")[0];
							console.log("IP:", g.getElementsByTagName("query")[0].textContent);
							console.log("City:", g.getElementsByTagName("city")[0].textContent);
							console.log("Country:", g.getElementsByTagName("country")[0].textContent);
						}
					}

					xhr.send();
				})();
				
			

The response data displayed in the browser console will be in the following format:

IP:
City:
Country: