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 Posting Data with jQuery

Maxim Melnic
Maxim Melnic
4,178 Points

What???

Explain in more detail how it works.

var url = $(this).attr("action");

and

var formData = $(this).serialize();

3 Answers

Hi Maxim

var url = $(this).attr("action");

This is grabbing the action from the form, when the form is submitted, usually what would happen is this action will get called and it tells the browser to send the form data to the action URL.

However in this example, we prevent the default as we don't want that to happen, we want to create our own AJAX request so we store the action in a variable named url.

var formData = $(this).serialize();

The serialize method creates URL encoded strings by serializing the values, these serialized results can then be used in our AJAX request, think of it like sanitizing the form data before we use it.

Hope this helps

Good Luck

Nicholas Wallen
Nicholas Wallen
12,278 Points

What if you have multiple forms on one page? How does it know which specific form you are pointing at?

it knows because of this keyword, so on form submit, get $(this) form data and action

Nicholas Wallen
Nicholas Wallen
12,278 Points

Maybe I need to go back and relook at the code, but was the form given an actual ID of "form"? How would it know which specific form if multiple forms were on a page, without somehow pointing to one by ID?

remedies
remedies
3,616 Points

The form was selected using $('form') which just selects the html tag. This makes it so any form submitted will also use this handler. If you'd like, you can create specific handlers for specific forms by using ID's like you've mentioned.

Example: $('#form1').submit(function(evt).... $('#form2').submit(function(evt)....