/    Sign up×
Community /Pin to ProfileBookmark

AJAX and call-backs

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();
}[/code]

From: [url]http://www.w3schools.com/ajax/[/url]

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);
}[/code]

From: [url]http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp[/url]

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.

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@KeverNov 02.2015 — I don't know which tutorial you refer to, but the URL shouldn't be inside the callback function. It should look like:<i>
</i>function loadDoc(url, type, cFunc) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 &amp;&amp; xhttp.status == 200) {
cFunc(xhttp);
}
}
xhttp.open(type, url, true);
xhttp.send();
}
×

Success!

Help @W8_4me spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...