Hi all,
This is my first time trying to use AJAX and my first time being introduced to the concept of call-backs and I was wondering if I’m understanding this correctly?
First here’s the code blocks/explanations:
Code block 1:
[code]function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(“demo”).innerHTML = xhttp.responseText;
}
}
xhttp.open(“GET”, “ajax_info.txt”, true);
xhttp.send();
}
From: [url]http://www.w3schools.com/ajax/
Code block 2:
Using a Callback Function
A callback function is a function passed as a parameter to another function.
If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.
The function call should contain the URL and what to do on onreadystatechange (which is probably different for each call):
Example
[code]function loadDoc(cFunc) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
cFunc(xhttp);
}
From: [url]http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
In the first code block, the open() method is coded after the xhttp.onreadystatechange = function()
Yet when performing a call-back, the tutorial is telling me to put the URL (presumably this means the open() method) inside a function called cFunc, but call cFunc inside the onreadystatechange > if () condition.
This appears to be contradictory. Am I reading this right?
Thank you.