DEV Community

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

Posted on

3 1 1 1 1

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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!

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay