We talked about GET in the last video but didn't give POST enough attention. So I thought we'd do that here. The big difference with POST is that you nearly always need to pass along data with the request. That data can take many forms, but it might just be an object you have around. The syntax is also easy:

$.post(
  "/data/process.php",
  {
    name: "Susan",
    job: "Writer"
  }
  function(data, textStatus, jqXHR) {
    // success
  }
);

Notice the second parameter which is an object (essentially JSON) of data. That data can be just about anything (including a string). It's on you to pass it in such a way that's useful to your backend.

Back to our form example from the last video, what if you wanted to pass along all the data from the entire form? You also didn't want to have to update the JavaScript when the form changed. jQuery makes that easy with its serialize() method. Just call it on the form element itself:

$("#my-form").serialize();

That will look through the entire form and make a query string out of each named input in the form. Then you can use that as the data you past when you $.post().

$("#my-form").on("submit", function() {
  $.post(
    "/",
    $("#my-form").serialize(),
    function(data, textStatus, jqXHR) {
      console.log("success");
    }
  );
});

See the Pen CtoEg by Chris Coyier (@chriscoyier) on CodePen

Comments

  1. User Avatar
    A Stevens

    Not quite getting this. If the data is sent from a form via the action(=”process.php”) why would I need ajax to do the same thing at the same time?
    Would be nice if there was an example with the complete process demonstrated

    • User Avatar
      someka
      Permalink to comment#

      Because when you hit the submit button you dont want the whole page to reload, you just want the “data sending->request receiving” process to happen silently in the background.

      Thats why it is common usage to preventDefault behaviour of the submit button when you do it with ajax (otherwise it would be non-sense as you mentioned)

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag