Skip to content

Instantly share code, notes, and snippets.

@tyler-boyd
Last active September 3, 2017 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyler-boyd/b2e014ade639ae8d1b034991063493a2 to your computer and use it in GitHub Desktop.
Save tyler-boyd/b2e014ade639ae8d1b034991063493a2 to your computer and use it in GitHub Desktop.
AJAX Form Submission

AJAX Form Submission

Disclaimer

You could do this with a 1-liner, but I'm going to try to explain the different parts (especially AJAX/callbacks) because they're complicated and interesting.

Hooking into the form's submit event

This is similar to other event handlers you've probably seen:

$('form#contact-form').submit( function(e) {
  var fd = new FormData(this); // "this" is the form tag element
  e.preventDefault();
});

I'd suggest testing this out by setting a breakpoint on the "preventDefault" line in devtools (go to inspect element, "Sources" tab, find the js file with this code, and click the line number to set a breakpoint) Official docs

So when the breakpoint is working, in the console you can enter "fd.get('somefield')" and it should print out the values.

So if you have <input name="email" />, then in the console run fd.get('email') and it will show the value the user entered.

Making an AJAX call

At it's simplest, you can do an AJAX call by:

$.post(url, data, successCallback)

In JavaScript, callbacks are the way asynchronous code (ie. AJAX requests) is handled. In C or Ruby, the next line of code only runs when the previous one finishes. In JS, you instead give it a "callback", which is a function that it runs when it's done.

So if you have

$.get("/", function(){alert("done");})
alert("second")

the "second" alert will show up before the "done" alert!

If this is confusing, don't worry too much about it yet. It's the main strength/weakness of JavaScript, and they're already moving to newer ways of doing things.

The general idea is if you're doing something that takes a long time (eg. an AJAX request), you don't want to wait for it to finish before moving on. So instead you just tell it what to run once it is finished.

This becomes really shitty when you have a lot of callbacks, and is called "callback hell".

If my explanation sucked, here's a pretty good one

Combining the two

As an example from the jQuery docs, it can be super simple to submit a form through ajax:

$('form#contact-form').submit(function(e) {
  $.post("http://someurl.com/", new FormData(this), function(){alert("Successfully sent email!");});
  e.preventDefault();
});

jQuery supports a ton of different ways of writing this:

$('form#contact-form').submit(function(e) {
  $.post(
    "http://someurl.com/", new FormData(this)
  ).done(
    function() { alert("Successfully sent email!"); }
  ).fail(
    function() { alert("Something went wrong!"); }
  );
});

The done function will be called if/when it succeeds, and the fail function will be called if/when the request fails. They can never both be called.

Going further

You can do more than just alerts in the done/fail callbacks!

Try displaying something more user-friendly, like adding a banner to the page saying if it worked or not.

Also, I didn't explain why callbacks are used in JS. Hint: if JS code takes a long time to run, the whole browser freezes until it finishes.

eg. paste this in devtools console, it will freeze the tab for 5 seconds (try scrolling).

var start = new Date()
for(;(new Date()).getTime() - start.getTime() < 5000;){}

Now imagine if instead of a dumb for loop, it was waiting 2 seconds for your AJAX request... and every time you did that, it froze!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment