DEV Community

Cover image for Send Form Data With Ajax
Yuba El Oualidi
Yuba El Oualidi

Posted on

Send Form Data With Ajax

Hello For Everyone !

Steps:

  1. Create an index.html file (HTML)
  2. Create a app.js file (JavaScript)

// You Can Also Style Your Form If You Need That !

HTML Codes:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>
       Send Form Data With Ajax 
       By (https://dev.to/yubaeloualidi)
    </title>
</head>
<body>
    <div id="message"></div>
    <form id="form">
        <input type="text" name="username" autocomplete="off" required="required" />
        <input type="password" name="password" autocomplete="new-password" required="required" />
        <button id="login" type="submit">Login</button>
    </form>

    <script src="app.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

JavaScript Codes:

const request = new XMLHttpRequest(),
    form = document.getElementById("form"),
    login = document.getElementById("login"),
    message = document.getElementById("message");

form.onsubmit = event => {
    event.preventDefault();
    const formData = new FormData(form);
    var body = "";

    for (const [key, value] of formData) {
        body += `${key}=${value}&`;
    }

    body = body.substring(0, body.length - 1);

    request.addEventListener('readystatechange', () => {
        if (request.readyState === 4 && request.status === 200) {
            console.log(JSON.parse(request.responseText));
        }
    })

    request.open('POST', 'read.php');
    // Warning: you need to change the request URL (read.php) with 
       your personal

    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
    request.send(body);
}

Enter fullscreen mode Exit fullscreen mode

When You Click on The Button (login), You Can Check if The request is sended in (web developers tool -> network -> your file)

Image description

Top comments (4)

Collapse
 
rodiongork profile image
Rodion Gorkovenko

Hi Friend! A bit funny to see guide to do this in plain JS in 2023 :) Anyway this could be nice for those willing to recap how it works in some cases.

I dare to recommend that in such articles, before "steps" you add small "motivation" - e.g. explain what you are going to show and when this can be useful :)

Collapse
 
artydev profile image
artydev

Thank you

Collapse
 
cezarytomczyk profile image
Cezary Tomczyk

I think you can pass formData directly to request.send(formData) and skip for-of loop as well as request.setRequestHeader.

Collapse
 
cataua profile image
Rogério Caetano

Great article! Simple and target to the point!