【Lecture8】Web Technologies
AJAX

AJAX is a developer’s dream, because you can:
- Update a web page without reloading the page
- Request data from a server – after the page has loaded
- Receive data from a server – after the page has loaded
- Send data to a server – in the background
What is AJAX
- AJAX is a request response pattern where the request is sent asynchronously (i.e. It is a “fire and forget” type of request, or non-blocking)
- A non-blocking request means that other things can load on the page while the request is being processed
- Allow you to inject content into the web page without having to reload the page
- You can only test/use AJAX on an actual web server due to security (prevents XSS or cross-site scripting attacks)
- AJAX won’t work locally
You can use this script as ajac.js
function inject(elemName, url){
var elem = document.getElementById(elemName);
injectNode(elem, url);
}
function injectNode(node, url){
var elem = node;
makeIdle(elem);
var xmlHttp = getXmlHttpRequest();
xmlHttp.open("get", url, true);
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4){
elem.innerHTML = xmlHttp.responseText;
}
}
xmlHttp.send(null);
}
function injectImage(elemName, imgName){
var elem = document.getElementById(elemName);
makeIdle(elem);
elem.innerHTML = '
';
}
function getXmlHttpRequest(){
var xmlHttp;
try{
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}catch(e){
// Internet Explorer
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
function makeIdle(elem){
elem.innerHTML = 'loading...'
}
Codes
Horizontal Line (HTML)
<hr>
<hr> tag creates the horizontal line on a web page.
toFixed() (JavaScript)
let num = 5.56789;
let n = num.toFixed(2);
consoel.log (n);
// Output: 5.57
This converts a number to a string. Also, this rounds the string to a specified number of decimals.