//-- What is Ajax --//
- asynchronous javascript & XML
- set of web technologies
- send & receive data asynchronously
- does not interfere with current web page
- JSON has replaced XML for the most part
//-- XML HttpRequest properties --//
- onreadystatechange
- readyState
- response
- responseText
- responseType
- responseURL
- responseXML
- status
- statusText
- timeout
- ontimeout
- upload
- withCredentials
//-- XML HttpRequest methods --//
- abort()
- getAllResponseHeaders()
- getResponseHeaders()
- open()
- overrideMimeType()
- send()
- setRequestHeader()
//-- Creating the Object --//
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}else{
//code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//-- Sending a Request --//
xhttp.open("GET","somefile.txt", true);
xhttp.send();
//-- Events --//
onReadyState - Stores a function to be called everytime the readyState changes
readyState - Holds the status of the XMLHttpRequest object (0-4)
0:request not initialized
1:server connection established
2:request received
3:processing request
4:request finished and response is ready
Statsus - Request status
200: OK
404: Page Not Found
//-- Example 1 --//
<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
</head>
<body>
<h1 id="mainText">Change This Text</h1>
<br>
<button onclick="changeText()">Change</button>
<script>
function changeText(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(xhttp.readyState == 4 && xhttp.status == 200){
document.getElementById('mainText').innerHTML = xhttp.responseText;
}
}
xhttp.open('GET', 'file.txt', true);
xhttp.send();
}
</script>
</body>
</html>