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 !


  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">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
       Send Form Data With Ajax 
       By (
    <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>

    <script src="app.js"></script>
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 => {
    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) {
    })'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;");

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)

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 :)

artydev profile image

Thank you

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.

cataua profile image
Rogério Caetano

Great article! Simple and target to the point!