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) jQuery and AJAX Introducing jQuery

Jordan C
Jordan C
6,249 Points

Why did he put the javascript inside of a function?

In this video, he puts the javascript inside of a function. Why does he do this?

nico dev
nico dev
20,364 Points

Exactly what Steven explained. Like Dave said in past videos of this course, AJAX requests require a callback function that will tell them what to do when they receive the response. That's the case here with this function.

I am doing the exact same course right now, so I happen to have the code available. Having said that, please take a look at the sendAJAX function. Now, take another look at the #load button. You probably already got it by now. They work together/combined, thanks to the onclick attribute in the latter.

In other words, the function acts like an event handler callback to the click in the mentioned button, and the load() bit alone is the one doing the AJAX magic (which probably emphasizes what Dave was saying about just how much jQuery simplifies the process and shortens the code).

Hint: Try commenting out the function and the call to the function from the click event... you'll see what happens.

HTH.

NOTE: Further readings (the latter, more specifically in the onclick section).

1 Answer

Steven Parker
Steven Parker
231,172 Points

That's probably a callback function.

You weren't very specific, but I'm guessing you're asking about a callback function. This is a common mechanism used by asynchronous processes.

In the case of an AJAX request, the system invokes your callback function when the state of the request changes. This allows the code you write to be executed later, such as when the requested data is available.