reply View all Tutorials & Projects

How to Create an AJAX Submit Form with JavaScript

You can use AJAX within JavaScript to create a form submission that does not require a page reload or redirection. This can enhance the user experience and you'll learn that from this tutorial.

Video Tutorial

Source Code

You can find the source code for this video below. Alternatively, browse it on GitHub.

README.md
# js-ajax-form-submission
A tutorial on using AJAX to submit HTML forms. Video Link: <coming soon>
check-login.php
<?php

    $username = isset($_POST['username']) ? $_POST['username'] : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';

    $ok = true;
    $messages = array();

    if ( !isset($username) || empty($username) ) {
        $ok = false;
        $messages[] = 'Username cannot be empty!';
    }

    if ( !isset($password) || empty($password) ) {
        $ok = false;
        $messages[] = 'Password cannot be empty!';
    }

    if ($ok) {
        if ($username === 'dcode' && $password === 'dcode') {
            $ok = true;
            $messages[] = 'Successful login!';
        } else {
            $ok = false;
            $messages[] = 'Incorrect username/password combination!';
        }
    }

    echo json_encode(
        array(
            'ok' => $ok,
            'messages' => $messages
        )
    );

?>
dashboard.html
<h1>Welcome!</h1>
index.html
<title>AJAX Forms - Web - dcode</title>
<link rel="stylesheet" href="http://youtube.local/assets/dcode.css">
<link rel="shortcut icon" href="http://youtube.local/assets/favicon.ico">

<style>
    #form-messages {
        background-color: rgb(255, 232, 232);
        border: 1px solid red;
        color: red;
        display: none;
        font-size: 12px;
        font-weight: bold;
        margin-bottom: 10px;
        padding: 10px 25px;
        max-width: 250px;
    }
</style>

<body>
    <h1>AJAX Forms - Web - dcode</h1>
    <div class="form">
        <ul id="form-messages"></ul>

        <label for="username">Username</label>
        <input type="text" id="username" spellcheck="false">

        <label for="password">Password</label>
        <input type="password" id="password">

        <button type="submit" id="btn-submit">Login</button>
    </div>
    <script>
        const form = {
            username: document.getElementById('username'),
            password: document.getElementById('password'),
            submit: document.getElementById('btn-submit'),
            messages: document.getElementById('form-messages')
        };

        form.submit.addEventListener('click', () => {
            const request = new XMLHttpRequest();

            request.onload = () => {
                let responseObject = null;

                try {
                    responseObject = JSON.parse(request.responseText);
                } catch (e) {
                    console.error('Could not parse JSON!');
                }

                if (responseObject) {
                    handleResponse(responseObject);
                }
            };

            const requestData = `username=${form.username.value}&password=${form.password.value}`;

            request.open('post', 'check-login.php');
            request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            request.send(requestData);
        });

        function handleResponse (responseObject) {
            if (responseObject.ok) {
                location.href = 'dashboard.html';
            } else {
                while (form.messages.firstChild) {
                    form.messages.removeChild(form.messages.firstChild);
                }

                responseObject.messages.forEach((message) => {
                    const li = document.createElement('li');
                    li.textContent = message;
                    form.messages.appendChild(li);
                });

                form.messages.style.display = "block";
            }
        }
    </script>
</body>

If you have any questions about this code, please leave a comment on the video.