AJAX

Introduction

AJAX (Asynchronous JavaScript and XML) is a technique for creating fast and dynamic web pages.
Web server sends only the structure of the page to client.
Web client runs JavaScript to request/submit data from/to different sources and modify webpage elements without reloading the page.

	
	Temperature: <span id="temperature"></span><p>
	Humidity: <span id="humidity"></span>

	<script>
		function loadDoc() {
			// url of gov weather data
			var url = "https://data.weather.gov.hk/weatherAPI/opendata/weather.php?dataType=rhrread&lang=en";
			// create a new XMLHttpRequest object
			var xhttp = new XMLHttpRequest();
			// function to be called when the request is completed
			xhttp.onreadystatechange = function() {
				// check if the request is completed and the response is ready (code 200)
				if (this.readyState == 4 && this.status == 200) {
					var data = JSON.parse(this.responseText);
					// display the temperature
					document.getElementById("temperature").innerHTML = data.temperature.data[1].value;
					// display the rainfall
					document.getElementById("humidity").innerHTML = data.humidity.data[0].value;
				}
			};

			// open a new request
			xhttp.open("GET", url, true);
			// send the request
			xhttp.send();
		}

		// call the function to load the data
		loadDoc();
	</script>
	

The HTML on consists of two titles and two empty spans with ID "temperature" and "humidity".
ajax
The JavaScript code sends a request to data.weather.gov.hk to get the weather data.
When the request is completed, text inside the spans are updated with the temperature and humidity data.

Advantages of AJAX in this example:
- Page is displayed immediately as the basic structure is simple HTML.
- Data is downloaded by browser (client) using JavaScript, so server does not need to process the data or run any scripts.

Task 1

Use AJAX to display the current weather icon based on data on data.weather.gov.hk and HKO

task

task

Task 2

Use AJAX to download temperature data from data.weather.gov.hk and display in a table

task

Reference

w3schools