Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) AJAX Concepts A Simple AJAX Example

eslam said
PLUS
eslam said
Courses Plus Student 6,734 Points

The callback function

I just wanna be sure that i get it, so as i understood that the callback function is where we put what we wanna do after we get a response from a server,

so the first step i must create XHR object to tell the browser that i wanna use ajax then the callback function its like im saying to the server after getting a response do 1 and 2 and 3 am i right ?

2 Answers

Ivan Penchev
Ivan Penchev
13,833 Points

While technically you are right, i would look at this official description for reference:

A function that takes other functions as arguments or returns functions as its result is called a higher-order function, and the function that is passed as an argument is called a callback function. It's named “callback” because at some point in time it is “called back” by the higher-order function.

This may sound a bit fleshy, but its important to understand where exactly is a callback placed in the hierarchy.

I know that your question was JUST related to AJAX, but callbacks are foundational block of javascript, they are used everywhere, please spend some time to learn them properly. https://teamtreehouse.com/library/callback-functions-in-javascript

Mayank Munjal
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Mayank Munjal
Front End Web Development Techdegree Graduate 18,120 Points

How is assigning the anonymous function to xhr.onreadystatechange a callback function? It's not being passed as an argument which I thought was necessary for a callback function!

Shivangi Sriv
seal-mask
.a{fill-rule:evenodd;}techdegree
Shivangi Sriv
Full Stack JavaScript Techdegree Student 261 Points

Hey Mayank Munjal , The XMLHttpRequest.onreadystatechange property contains the event handler to be called when the readystatechange event is fired, that is every time the readyState property of the XMLHttpRequest changes , the event handler is called and the function gets executed. Syntax--

XMLHttpRequest.onreadystatechange = callback;