Hướng dẫn Submit HTML Form with AJAX

22nd Feb 2022
Table of contents

Ví dụ sau minh họa một biểu mẫu HTML5 truy cập dữ liệu thông qua lệnh gọi API Ajax bằng cách sử dụng phương thức POST.  Call ajax sẽ được xử lý bởi một tài nguyên REST được viết bằng xml.

HTML5 Form with submit input

When the end-user inputs the data in the form and clicks the submit button the form data is sent with the HTTP POST method, this data onsubmit function catches the data and with the help of the xhr.send request sends the data to the respective URL.

<form id="login-form">
    <div class="form-group">
        <label for="xuser">Username</label>
        <input type="text" name="iuser" class="form-control" />
    </div>
    <div class="form-group">     
        <label for="xpass">Password</label>
        <input type="password" name="xpass" class="form-control" />
    </div>  
    <input type="hidden" name="redirect" value="home-page" />
    <input type="submit" class="btn btn-danger" value="Submit" class="form-control" />
</form>

Keys things to keep in mind in HTML5 form

  • All the input elements should be inside the form tag.
  • No need of action or method atttribute. action="/tests/v1.0/form" or method="POST"
  • Keep submit input in the form <input type="submit" />

The form can be decorated with CSS and this does not affect the functionality. The javascript API will not work if above things are not kept in the form.

Javascript Ajax Form Submit

All the input fields including hidden fields will be sent on the server without any extra javascript. This is thanks to the FormData API.

Pass the form object to FormData constructor to populate the form object.

The FormData object contains all the fields as name attribute of input fields <input name="iuser" />, Using the FormData.get() API, each form value can be fetched.

//get the form from DOM (Document object model)
    var form = document.getElementById('login-form');
    form.onsubmit = function(event){
        var xhr = new XMLHttpRequest();
        var data = new FormData(form);
        //Add extra data to form before submission.
        data.append("referer","https://example.com");
        //open the request
        xhr.open('POST','http://localhost:7000/tests/v1.0/form')
        //send the form data
        xhr.send(data);

        xhr.onreadystatechange = function() {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                form.reset(); //reset form after AJAX success.
            }
        }

        //Dont submit the form.
        return false;
    }

If additional parameters needs to be send in the form, they can be appended to the FormData object.

Dont forget the last line. The onsubmit function should always return false,indicating to HTML5 Form API that form should not be submitted.

Send form data in json format

FormData object holds key-value pairs, as we can see in the above example.We need to conver these key-value pairs into an object.

The Object.fromEntries() method transforms a list of key-value pairs into an object.

xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var json = JSON.stringify(Object.fromEntries(formData));
xhr.send(json);

We cannot directly send the object over the network. Object needs to be converted into a json string and sent using xhr.send method.

It is important to let the server know, we are sending the data in json format using the Content-Type header.

Handling AJAX Submit response in javascript

After submit operation, we can wait for the respone and reset the form once success response is recieved. We can do other operations like

  • Show success message to user
  • Redirect to other page
  • Remove HTML5 element from page
  • Reset the form
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        form.reset(); //reset form after AJAX success.
    }
}

Submit form with fetch

Fetch is a browser APIs which allows sending HTTP requests. In the below example we have replaced XHR with fetch.

var form = document.querySelector('form');
form.onsubmit = function(event){
    var formData = new FormData(form);

    fetch("/test.php",
    {
       body: formData,
       method: "post"
    }).then();

    //Dont submit the form.
    return false;
}

On the Network

The form-data format for sending data over the network to the server.

Ajax form

The parameters sent in the POST request are received on the server. The parameters on the server can be accessed using name attribute value given in the form.

To understand how POST request works in ajax call, checkout GET vs POST in REST API.

Bạn thấy bài viết này như thế nào?
1 reaction

Add new comment

Image CAPTCHA
Enter the characters shown in the image.
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”

Related Articles

String là một kiểu dữ liệu thông dụng trong nhiều ngôn ngữ lập trình, nó mạnh vì nó có thể dùng vào nhiều trường hợp để giải quyết các vấn đề

Nếu bạn muốn người dùng cung cấp tên, tuổi, email… ta cần một hàm Javascript  để đảm bảo rằng họ đã nhập với các thông tin này

The character jumping around the page was caused by having to finish the animation to the next unit before going on to the next key.

Gọi phương thức postMessage của phần tử window / iframe mà bạn muốn gửi thông tin tới.