Create Dynamic Forms with AJAX

Create Dynamic Forms with AJAX

Basic Form

On many websites, it is common to come across a form asking you to enter your email address. No further than on this page, you have one (Which appears when you click on the blue button) allowing you to subscribe to my newsletter. All forms are based on a common principle : Sending information to a page, which then saves and processes it. Here is what the form mentioned above looks like :

 

<form action="newsletter.php" method="post">
    <input type="text" name="name" placeholder="Name (Bill)"/>
    <input type="email" name="email" placeholder="Email Address (bill@example.com)"/>
    <input type="submit" value="Send"/>
</form>

 

This form has three elements :

• A text field, where you can enter your name.

• An email field, where you can enter your email address.

• A submit field, allowing you to send the form.

The core of the form is the third field. When you click on it, your browser will redirect you to a new page, sending the information you have entered. The page in question, as well as the method of sending, are indicated in the attributes of the form tag. In this example, the page is newsletter.php, and the method is POST. Regarding the different existing sending methods, we will have the opportunity to discuss them later in this article.

As it stands, this code is fully functional. But it has a major disadvantage : The change of page, caused by the sending of the form. For a newsletter subscription, this is not a real problem. But let's say you want to do a real-time messaging. Sending each of your messages would cause the page to reload completely. Concerning the reception of new messages, the problem would be even worse : Since you cannot retrieve data once the page is loaded, you would have to force it to update every second, (And take advantage of its generation to retrieve potential new messages) which would pose serious ergonomic problems…

As you will have understood, it is impossible to create a real instant messaging using traditional forms, because of this imposed page change. To overcome this limitation, JavaScript provides a method that allows us to make requests in the background, without imposing a page change : AJAX. (Asynchronous JavaScript And Xml)

The principle consists in sending an asynchronous request in the background, specifying the data to be sent. Like any request, it will receive a response that, when processed in JavaScript, will allow the main page to be modified, depending on the data received. As with the use of flexbox, it is a simple concept to master, and offers you many possibilities afterwards.

Add AJAX on a form

First of all, it is important to specify that the functioning of AJAX and forms is quite similar. As a result, you will often use AJAX in addition to a traditional HTML form. We will add a JavaScript file, the purpose of which will be to modify our form, so that it uses AJAX. And for that, we will use jQuery.

Why jQuery ? In absolute terms, its use is not mandatory to use AJAX. However, it will simplify the sending of our requests, and allow us to process their responses in a few lines. If you have never used jQuery before, don't worry ! We will only use a few simple functions, which I will detail when we need them.

To start, you will need to include jQuery in our HTML file. For this, I recommend that you use a CDN, in order to have a simple link to add at the top of your page.

  <script src="https://code.jquery.com/jquery-3.4.1.min.js"> </script>  

Once this is done, we will add a new script to our file. The purpose of this script will be, as explained above, to modify our form, so that it uses AJAX. To achieve this, we will use the jQuery submit method on our form.

As a reminder, jQuery allows you to retrieve an element of a page using the $ method, (Yes, the dollar method) using a CSS selector as a parameter. I therefore advise you to add an id to the form, in order to be able to retrieve it by this means.

Concerning the submit method, it takes as parameter a callback function. Callback functions are inseparable from JavaScript, and allow actions to be taken in response to a given event. With submit, the callback function will be called when the corresponding form is sent. To start, I suggest that you simply display a message on the screen when you send the form.

 

<!DOCTYPE HTML>

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"> </script>
        <script>
            $("#messagingForm").submit(function() {
                alert("Hello World !");
            });
        </script>
    </head>
    <body>
        <form id="messagingForm" action="newsletter.php" method="post">
            <input type="text" name="username" placeholder="Username (Bill75)"/>
            <input type="text" name="message" placeholder="Message (Hello World !)"/>
            <input type="submit" value="Send"/>
        </form>
    </body>
</html>

 

If you test this code, you should see… That it doesn't work !

When you click on the send button, the form starts its default operation, and redirects you to the target page. The callback function is well executed, but is invisible to us because of the redirection. To fix this, you have to annihilate this default behavior.

With jQuery, this is done in two steps. First, we need to retrieve the form event. This one is sent as a parameter of the callback function, and it is enough to retrieve it like any other parameter. Then, you must call the preventDefault method of this parameter, which will suspend its execution.

 

$("#messagingForm").submit(function(event) {
    event.preventDefault();
});

 

Send the Request

Our form is now ready ! All we have to do now is implement the AJAX request inside the callback function. Before going any further, I would like to come back to the methods of sending, which I briefly discussed at the beginning of this article. When you need to transfer data to a page, there are mainly two possible sending methods :

• GET : The data sent passes through the URL. The generated links are of the form index.php?name=Anthony&message=Hello%20World%20!. This method is especially useful when you send very short data.

• POST : The data passes through the HTTP headers. This means that they are sent separately, so the URL remains simple. This method allows you to send longer data.

Except in specific cases, I recommend that you use the POST method, which has only advantages. But whatever method you use, there will be no difference in its use. Indeed, jQuery provides the get and post methods, whose use is strictly identical. The only difference is the method of sending the data, within the function.

Let's find out right away how to use these methods. They take at least one parameter, corresponding to the page that must be opened. But most of the time, you will indicate a second parameter, corresponding to the data to be sent. (Data that will be transferred using the GET or POST method, depending on the function used) In our case, we must send the data corresponding to the different fields of the form.

 

$("#messagingForm").submit(function(event) {
    event.preventDefault();

    $.post("newsletter.php", {
        "name" : "Anthony",
        "message" : "Hello World !"
    });
});

 

As you may have noticed, we always send the same values for name and message. (Respectively "Anthony" and "Hello World !") It would be more interesting to retrieve the values entered by the user in the form.

Once again, jQuery will simplify our lives. We just need to retrieve one of the fields of the form, and we will be able to access its value (Input by the user) with the method val. I therefore invite you to add an id to each field of the form, as we did with the form itself.

 

<!DOCTYPE HTML>

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"> </script>
        <script>
            $("#messagingForm").submit(function(event) {
                event.preventDefault();

                $.post("newsletter.php", {
                    "name" : $(".messagingUsername").val(),
                    "message" : $(".messagingMessage").val()
                });
            });
        </script>
    </head>
    <body>
        <form id="messagingForm">
            <input id="messagingUsername" type="text" name="username" placeholder="Username (Bill75)"/>
            <input id="messagingMessage" type="text" name="message" placeholder="Message (Hello World !)"/>
            <input type="submit" value="Send"/>
        </form>
    </body>
</html>

 

You will notice that I have deleted the action and method attributes from the form, because they will no longer be used.

While trying this code, you should notice that your button seems to be unresponsive… And yet, every time you click on it, your browser opens the newsletter.php page in the background, sends the data you filled in in the form, and closes the page without you even noticing anything.

Congratulations, you have just made your first AJAX request !

Loading the Response

Now that you know how to send data using AJAX, you are able to create a real-time messaging system ! Well, almost… You know how to send data to a page, but not how to get it back. For that, nothing very complicated, jQuery takes care of everything for us. In fact, the request we created already intercepts his answer. All that remains for us to do is to react to this response, depending on its content.

To do this, simply add a third parameter to the get or post function, corresponding to a new callback function. This function, which will be executed when the request is completed, takes a rather particular parameter, which is the answer to your request. Most of the time, this answer is in HTML format, but it is possible that it is JSON, XML, or any other format…

For example, we can display this answer, to check the status of our request. Obviously, the page called up will have to display whether or not the message has been correctly recorded.

 

$("#messagingForm").submit(function(event) {
    event.preventDefault();

    $.post("newsletter.php", {
        "name" : $(".messagingUsername").val(),
        "message" : $(".messagingMessage").val()
    }, function(response) {
        alert(response);
    });
});

 

Note : Depending on the answer you get, you will perform different actions. For example, if the reply contains a new message, you will add it to the discussion list, rather than displaying it as here.

In practice, we can distinguish two cases. If the called page is to record data, (Like there) we can simply display that the message has been recorded. (If this is the case, or otherwise display an error message) In the second case, the page retrieves data, such as the list of new messages, and you must then process them in order to integrate them into your web page. There are many possibilities, depending on the type of data received, and that is why I cannot present you with all possible situations.

Finally, I would like to conclude with one last important point : We have seen in this article an example of a script that manages requests in the background, to send and receive messages. On many sites, you will not have a single script like this one, but several dozen running in parallel. What I showed you is a simple example. In practice, we would have a first script to send the messages, and a second one that would run every second, and whose purpose would be to retrieve the new messages. It is preferable that each AJAX request has a unique mission, in order to keep a clear and easily understandable code !

From now on, I encourage you to use AJAX on all your forms. Its handling is both simple and fast, and only brings benefits to visitors to your website. Its asynchronous use is ubiquitous in JavaScript, making it a strong learning argument for any developer.

Written by Pythony on the 12/15/2019.

What did you think of this article ?

Other Articles

Hello World from Pythony

Hello World from Pythony

When starting a new programming language, the tradition is to start with a program that displays the message "Hello World !" on the screen. And it is also with this message that I wanted to start my first article on this blog. During my life, I have had the opportunity to work on many projects, and this site is one of them. For many years, I have dreamed of being able to live off my passion, and I am about to do so

Read "Hello World from Pythony"
Optimize your Applications with Multithreading

Optimize your Applications with Multithreading

An application developed with a programming language is a sequence of instructions, executing one after the other. However, such an operation has a major disadvantage, which is the dependence of each instruction on the previous instructions. As a result, the slightest slowdown in one of these operations may impact your entire application

Read "Optimize your Applications with Multithreading"
Dare to Retrain in Computing

Dare to Retrain in Computing

Career transition is a question that everyone has asked themselves during their career. If you don't enjoy getting up in the morning anymore, and you're counting the days until your next weekend, it's time to think about it seriously

Read "Dare to Retrain in Computing"