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

eslam said
eslam said
Pro Student 6,733 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,832 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.

Mayank Munjal
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!

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;