Save form data to text file – HTML & Javascript Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Save form data to text file – HTML & Javascript without wasting too much if your time.

The question is published on by Tutorial Guruji team.

{"username":"Lorem", "password":"ipsum"} 
if (
    && isset($_POST["username"])
    && isset($_POST["password"])
) {
    $json = json_encode($_POST);
    // Save JSON to file
    file_put_contents("user.json", $json);
    // Return some data back to the AJAX request.
    echo $json;
    // PS it's not wise to send passwords that way. 
<!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">
    <link rel="shortcut icon" href="#!" type="image/x-icon">
    <title>AJAX PHP - SAVE USER DATA </title>


    <h1>User: <span data-username>Unknown</span></h1>

    <form id="form-login" action="./save.php" method="post">
        <div class="form-group">
                <input placeholder="Username" autocomplete="off" type="text" name="username">
        <div class="form-group">
                <input placeholder="Password" autocomplete="off" type="password" name="password">
        <input id="button1" class="btn btn-success" type="submit" value="Login">

        const EL_formLogin = document.querySelector("#form-login");
        EL_formLogin.addEventListener("submit", (ev) => {
            ev.preventDefault(); // Stop default form submit - we'll use AJAX
            fetch(EL_formLogin.action, {
                method: 'POST',
                body: new FormData(EL_formLogin),
            }).then(res => res.json()).then(data => {
                // Hide the form
                EL_formLogin.hidden = true;
                // Show the user name
                document.querySelector("[data-username]").textContent = data.username;

We are here to answer your question about Save form data to text file – HTML & Javascript - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji