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

Omar Khalil
Omar Khalil
2,767 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
174,085 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,767 Points

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

thanks anyway

Steven Parker
Steven Parker
174,085 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,767 Points

Well, somehow yes thanks