How To Submit a Form Using XMLHttpRequest in Javascript

Reading Time: 6 minutes
7,125 Views

Inside this article we will see how to submit a form using XMLHttpRequest in javascript. Article contains a classified information about sending form data to server using Post request type.

In javascript we use XMLHttpRequest for ajax requests. Additionally if you don’t have any idea about how to use XMLHttpRequest then also you will get some idea from it.

We will consider a HTML form with few input elements. Submit this form using XMLHttpRequest in javascript.

The keystone of AJAX is the XMLHttpRequest object.

  1. Create an XMLHttpRequest object
  2. Define a callback function
  3. Open the XMLHttpRequest object
  4. Send a Request to a server

Learn More –

Let’s get started.


Create an Application

Create a folder with name js-ajax in your localhost directory. Create files index.html and server.php into it.

index.html will contain HTML form and also the code which submits form data to server. server.php file process form data and returns a response to client.

Open index.html and write this complete code into it.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Form Submit Using XMLHttpRequest in Javascript</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>

    <div class="container">
        <h4>Form Submit Using XMLHttpRequest in Javascript</h4>
        <div class="panel panel-primary">
            <div class="panel-heading">Form Submit Using XMLHttpRequest in Javascript</div>
            <div class="panel-body">
                <form class="form-horizontal" action="javascript:void(0);" id="frmdata" onsubmit="submitFormData(this)">
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="name">Name:</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="name" name="name" placeholder="Enter name">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="email">Email:</label>
                        <div class="col-sm-10">
                            <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-success">Submit</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // handle form submit
        function submitFormData(event) {

            // form values
            var name = event.name.value;
            var email = event.email.value;

            var http = new XMLHttpRequest();

            var url = 'server.php';
            var params = 'name=' + name + '&email=' + email;
            http.open('POST', url, true);

            //Send the header information
            http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

            http.onreadystatechange = function() {
                if (http.readyState == 4 && http.status == 200) {
                    alert("Form submitted successfully");
                    document.getElementById("frmdata").reset();
                    console.log(http.responseText);
                }
            }

            // Send params with request
            http.send(params);
        }
    </script>
</body>

</html>

Here,

When we click on submit button, it runs submitFormData() function.

Submit handler function receiving form values by this code –

var name = event.name.value;
var email = event.email.value;

Create an instance of XMLHttpRequest –

var http = new XMLHttpRequest();

Prepare form data which will be send to server –

var params = 'name=' + name + '&email=' + email;

http.send(params);

Open connection to send data via POST method –

http.open('POST', url, true);

On state change of instance, we will get server response –

http.onreadystatechange = function() {
    if (http.readyState == 4 && http.status == 200) {
        alert("Form submitted successfully");
        document.getElementById("frmdata").reset();
        console.log(http.responseText);
    }
}

Open server.php and write this code into it.

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    echo json_encode(
        array(
            "status" => 1,
            "message" => "Form submitted",
            "data" => $_POST
        )
    );
}

exit;

This is checking for submission via POST request type and simply returning the submitted form data. You can add any other code here for data like save in database, etc.


Application Testing

Open browser and type this –

URL – http://localhost/js-ajax/index.html

It will show a simple form with Name & Email as two input fields. When you submit, after getting server response it will show you a alert.

Here , is the image of HTML form and request processing via server.php

We hope this article helped you to learn How To Submit a Form Using XMLHttpRequest in Javascript Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more