DEV Community

Cover image for Save forms temporary data
jdsaraiva
jdsaraiva

Posted on

Save forms temporary data

By now you should have come to a point were you already coded some forms.
Used HTML to structure your form, JavaScript to get the data and PHP to save it, right ?
Maybe you have come to a point where you have a consistent form, with several inputs and options, however if this data isn’t validated on the server side the page will refresh and all the users inputs will be lost… obviously causing some frustration.

With this simple snippets my goal is to show you how to implement an almost generic form functions that will fetch the inputs values, save them on a temporary session variable and if something goes wrong the values are loaded again on the form.
This way you can have a safer server side validation and you visitors won’t have to refill the values if something goes wrong.
Let’s start with a really basic form (form.php);

<?php }

   // check if data is valid
   if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {

      echo("e-mail is not valid");

      // Something went wrong, load the user's data
      loadSessionVariables();

   } else {

echo "Welcome " . $_POST["name"] . ", you e-mail is: " . $_POST["email"];

   }

}

?>

<form action="form.php" method="post">

   First name:<br>
   <input required type="text" name="name"><br>

   E-mail:<br>
   <input required type="text" name="email"><br><br>

   <input onClick="saveData()" type="submit" value="Submit">

</form>

As you can see we have a basic form that gets the data and displays it.
Normally this data would be saved on a database of have further processing, although for the sake of simplicity we are just displaying it.
We will start by looping the form and save it’s input data, with this function:

function saveData(){

const forms = document.querySelectorAll('form');
    const form = forms[0];

    let array = [];
    [...form.elements].forEach((input) => {
        if ( input.type === "text" )  array.push(input.value);
    });

    sessionStorage.setItem("form-data", JSON.stringify(array ));
}

And if an error is detected we can load the data again with this one:

function loadSessionVariables(){ ?>

document.addEventListener("DOMContentLoaded",function(){

        if (sessionStorage.getItem("form-data")) {

            const forms = document.querySelectorAll('form');
            const form = forms[0];
            let retrievedData = sessionStorage.getItem("form-data");
            retrievedData = JSON.parse(retrievedData);
            let index = 0;

            [...form.elements].forEach((input) => {
                if ( input.type === "text") {
                    input.value  = retrievedData[index];
                    index++;
                }
            });

            sessionStorage.clear();

        }

    });

Overall you can find all the code here: https://github.com/jdsaraiva/Save-forms-temporary-data

Hope this simple code can help you to tackle this issue and make your website even more user friendly.

Let me know if it helped you out.
Best regards, João Dessain Saraiva.

Top comments (0)