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.