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

Omar Khalil
Omar Khalil
2,769 Points

what is the point of creating the callback function before sending the request?

The structure of an ajax request is: create an XMLhttp object > create a call back function > open a request > send a request

why can't it be like this : create an XMLhttp object > open a request > send a request> create a call back function

what is the point of creating the callback function before sending the request?

2 Answers

Steven Parker
Steven Parker
231,269 Points

The callback must be associated with the XHR before you perform any operations on it, because it will be needed to handle state change events. Since these events can happen at any time, your callback must be ready for them.

Omar Khalil
Omar Khalil
2,769 Points

with all respect, but your answer doesn't answer the question at all.

thanks anyway

Steven Parker
Steven Parker
231,269 Points

Maybe a simile would convey the point better:
Creating the callback after sending the request would be like buying fire insurance after your house burns down.

Just like insurance, the callback must already be there to handle the events that will happen at times you cannot predict.

Does that clarify the answer?

Omar Khalil
Omar Khalil
2,769 Points

Well, somehow yes thanks