JavaScript AJAX Basics (retiring) jQuery and AJAX Posting Data with jQuery

Maxim Melnic
Maxim Melnic
4,177 Points

What???

Explain in more detail how it works.

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

and

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

3 Answers

Liam Clarke
MOD
Liam Clarke
Treehouse Moderator 19,244 Points

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?

Liam Clarke
MOD
Liam Clarke
Treehouse Moderator 19,244 Points

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)....