Pinterest Stumbleupon Whatsapp
Advertisement

You may have read our jQuery guide A Basic Guide to JQuery for Javascript Programmers A Basic Guide to JQuery for Javascript Programmers If you are a Javascript programmer, this guide to JQuery will help you start coding like a ninja. Read More , as well as part five of our jQuery tutorial on AJAX jQuery Tutorial (Part 5): AJAX Them All! jQuery Tutorial (Part 5): AJAX Them All! As we near the end of our jQuery mini-tutorial series, it's about time we took a more in-depth look at one of the most used features of jQuery. AJAX allows a website to communicate with... Read More , but today I’ll be showing you how to use AJAX to dynamically send a web form. JQuery is by far the easiest way to use AJAX, so checkout our getting started tutorial jQuery Tutorial - Getting Started: Basics & Selectors jQuery Tutorial - Getting Started: Basics & Selectors Last week, I talked about how important jQuery is to any modern web developer and why it's awesome. This week, I think it's time we got our hands dirty with some code and learnt how... Read More if you’re a beginner. Let’s jump right in.

Why Use AJAX

You may be wondering “Why do I need AJAX?” HTML is perfectly capable of submitting forms, and does so in a fairly painless way. AJAX is implemented in a large majority of webpages, and its popularity continues to rise.

AJAX

The huge benefit AJAX brings is the ability to partially load parts of webpages. This makes pages appear faster and more responsive, and saves bandwidth by only having to reload a small portion of data instead of the whole page. Here are some basic AJAX use cases:

  • Check for new emails regularly.
  • Update a live football score every 30 seconds.
  • Update the price for an online auction.

AJAX provides you, the developer, with a nearly unlimited ability to make webpages fast, responsive, and snappy — something that your visitors will thank you for.

The HTML

Before getting started, you need a HTML form. If you don’t know what HTML is, then read our guide on how to make a website for beginners How to Make a Website: For Beginners How to Make a Website: For Beginners Today I'll be guiding you through the process of making a complete website from scratch. Don't worry if this sounds difficult. I'll guide you through it every step of the way. Read More .

Advertisement

Here’s the HTML you need:

<!DOCTYPE html>
<html>
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
	<script type="text/javascript">

	</script>
</head>
<body>

	<form action="some/file" method="POST" name="myForm" id="myForm">
		Name:
		<input type="text" name="name">
		Age:
		<input type="text" name="age">
		<input type="submit">
	</form> 

</body>
</html>

Initial HTML Form

This html defines a form with a few elements. Notice how there are action and method attributes. These define where and how the form is submitted. They are not needed when you are using AJAX, but it’s a good idea to use them, as it ensures that visitors to your website can still use it if they have JavaScript disabled. This page includes jQuery hosted by Google on their CDN What CDNs Are & Why Storage Is No Longer An Issue What CDNs Are & Why Storage Is No Longer An Issue CDNs make the Internet fast and websites affordable even when you scale to millions of users. Firstly, bandwidth costs money; those of us on limited contracts know that all too well. Not only do you... Read More . The head contains a script tag — this is where you will write your code.

This form may look a bit boring right now, so you may want to consider learning CSS 5 Baby Steps To Learning CSS & Becoming A Kick-Ass CSS Sorcerer 5 Baby Steps To Learning CSS & Becoming A Kick-Ass CSS Sorcerer CSS is the single most important change webpages have seen in the last decade, and it paved the way for the separation of style and content. In the modern way, XHTML defines the semantic structure... Read More to liven it up a bit.

The JavaScript

There are several ways you can submit forms with JavaScript. The first and easiest way to do so is through the submit method:

document.getElementById('myForm').submit();

You can of course target the form with jQuery if you prefer — it makes no difference:

$('#myForm').submit();

This command tells your browser to submit the form, exactly like pressing the submit button. It targets the form by its id, and in this case, that’s myForm. This is not AJAX, so it will reload the whole page — something that’s not always desirable.

In the method attribute of your form, you specified how to submit the form. This can be POST or GET. This attribute is not used when submitting forms using AJAX, but the same method can be used.

Much of the modern web is run off GET or POST requests. Generally speaking, GET is used to retrieve data, while POST is used to send data (and return a response). Data can be sent with GET, but POST is nearly always the better choice – particularly for form data. You may have seen GET requests before — they send the data attached to the URL:

somewebsite.com/index.html?name=Joe

The question mark tells the browser that any data immediately following it is not to be used to traverse the website, but should instead be passed through to the page for it to process. This works well for simple things like a page number, but it has some drawbacks:

Maximum character limit: There is a maximum number of characters that can be sent in a url. You may not have enough if you are trying to send a large amount of data.
Visibility: Anybody can see the data being sent in a GET request — it’s no good for sensitive data such as passwords or form data.

Ajax Response Code

POST requests work in a similar way, only they do not send the data in the URL. This means a larger amount of data can be sent (data is known as a payload), and some security is gained by not exposing the data. The data can still be easily accessed though, so look into an SSL certificate What Is an SSL Certificate, and Do You Need One? What Is an SSL Certificate, and Do You Need One? Browsing the Internet can be scary when personal information is involved. Read More if you want total peace of mind.

Whether POST or GET is used, data is sent in key -> value pairs. In the URL above, the key is name, and the value is Joe.

The better way to submit forms is to use Asynchronous JavaScript and XML (AJAX). JavaScript supports AJAX calls, but they can be confusing to use. JQuery implements these exact same methods, but does so in an easy to use way. You can instruct your browser to perform a GET or POST request — stick to POST for this example, but GET requests are performed in a similar manner.

Here’s the syntax:

$.post('some/url', $('#myForm').serialize());

This code does several things. The first part ($) lets your browser know that you want to use jQuery for this task. The second part calls the post method from jQuery. You have to pass in two parameters; The first is the url to send the data to, while the second is the data. You may find (depending on the URL you are trying to access), that your browsers’ same-origin security policy may interfere here. You can enable cross-origin resource sharing to get round this, but simply pointing to a URL hosted on the same domain as your page is often enough.

The second parameter calls the jQuery serialize method on your form. This method accesses all the data from your form, and prepares them for transmission — it serializes them.

This code alone is enough to submit a form, but you may find things act a bit strange. It’s well worth investigating your browser developer tools, as these make debugging network requests a breeze.

Browser Console Tools

Alternatively, Postman is an excellent free tool for testing HTTP requests.

If you want to submit your form using AJAX when the submit button is pressed, that’s just as easy. You need to attach your code to the submit event of the form. Here’s the code:

$(document).on('submit','#myForm',function(){
 $.post('some/url', $('#myForm').serialize());
 return false;
});

This code does several things. When your form is submitted, your browser comes and runs your code first. Your code then submits the form data using AJAX. The final step required is to prevent the original form from submitting — you have already done this with AJAX, so you don’t want it to happen again!

If you want to perform some other task once the AJAX has finished (or maybe even return a status message), you need to use a callback. JQuery makes these very easy to use — simply pass a function as another parameter like this:

$.post('url', $('#myForm').serialize(), function(result) {
 console.log(result);
}

The result argument contains any data returned by the url the data was sent to. You can easily respond to this data:

if(result == 'success') {
 // do some task
}
else {
 // do some other task
}

That’s it for this post. Hopefully you now have a solid understanding of HTTP requests, and how AJAX works in the context of a form.

Did you learn any new tricks today? How do you use AJAX with forms? Let us know your thoughts in the comments below!

Image Credits: vectorfusionart/Shutterstock

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. Shahbaz
    August 25, 2017 at 11:34 am

    Hello Sir! This is awesome post. Thank you!.....