Hello For Everyone !
Steps:
- Create an index.html file (HTML)
- 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>
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);
}
When You Click on The Button (login), You Can Check if The request is sended in (web developers tool -> network -> your file)
Top comments (4)
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 :)
Thank you
I think you can pass
formData
directly torequest.send(formData)
and skipfor-of
loop as well asrequest.setRequestHeader
.Great article! Simple and target to the point!