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

Jeremiah Lugtu
Jeremiah Lugtu
9,910 Points

What does the url and formData do? Can anybody expound on what is happening internally? Starts at 3:35

var url = $(this).attr("action");
  1. what is 'this'? the form? or the action attribute? (if it's the form, what are we doing with the action attribute?)
  2. what are we doing here?
var formData = $(this).serialize();
  1. what? -the MDN doesn't help... :( *is there another example aside from the MDN that uses .serialize()?

after the process is done, how will we know the form was submitted? It looks like it was just replaced by the p tag.

or is there a server-side to all of this madness?

1 Answer

As he says, this line selects the form and pulls out its action attribute. The keyword this refers to the form:

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

This line selects the form again and runs the serialize data on it. Think of serializing as putting the form data into query string format.

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

These two parts are needed for the post.

So, if the user fills in their name (Jeremiah) and email (jLugtu@gmail.com), and the action was handleForm.php, then, if the form method was GET (and it wasn't using jQuery), the url would be

handleForm.php?name=Jeremiah&email=jLugtu@gmail.com

In this video, however, he's using jQuery and its post() method, not get, which sends the same data, but not in the query string. When handleForm.php on the server gets the post, if it is set up properly it will read the value for name and email and put them into PHP variables. And if it's done right it's not really madness.

Here's the URL for documentation on jQuery's serialize() method: https://api.jquery.com/serialize/

There's also a demo.