PHP saves form information after submitting the form

Hi I am creating a form in the mvc system view and I want all inserted values ​​to be saved in case of form failure. How to do this: I tried (example for the field):

     <label for="user_firstname">Nume</label>
    <input id="user_firstname" type="text" name="user_firstname" value=<?= $_POST['user_firstmane'] ?> >
    <? if (isset($errors['user_firstname'])): ?>
    <span class="error"><?= $errors['user_firstname']; ?></span>
<? endif; ?> 

but of course it doesn't work the first time (when no action is taken).

What is the easiest way to do this? any ideas?

Thank you

+3
source share
5 answers

I would suggest something like:

<label for="user_firstname">Nume</label>
    <input id="user_firstname" type="text" name="user_firstname" value=<?(isset($_POST['user_firstname']) ? $_POST['user_firstname'] : ""; ?>>
    <? if (isset($errors['user_firstname'])): ?>
    <span class="error"><?= $errors['user_firstname']; ?></span>
<? endif; ?> 

You also had a typo in $ _POST ["user_firstmane"] should be $ _POST ["user_firstname"] :)

+1
source

Just skip the DOM in javascript and put the PHP $ _POST data in input.value value

<script type='text/javascript'>

<?php
    echo "var jsArray = new Array();";
    foreach ($_POST as $key=>$value){
        echo "jsArray['$key'] = '$value';";  //turn it into a javascript array
    }
?>


        // Grab all elements that have tagname input
        var inputArr = document.getElementsByTagName("input");

        // Loop through those elements and fill in data
        for (var i = 0; i < inputArr.length; i++){
            inputArr[i].value = jsArray[inputArr[i].name];

        }

</script>
+2
source
value="<?php echo isset($_POST['user_firstname'])? $_POST['user_firstname'] : "" ?>"
+1

, , ? $_SESSION . :

check.php

<?php
   session_start();
   if (strlen($_POST['user_firstname']) < 5) { //for example
       $_SESSION['user_firstname'] = $_POST['user_firstname'];
   }
?>

In your current form. change value=<?= $_POST['user_firstmane'] ?>to value="<?=$_SESSION['user_firstname']?>"therefore:

<label for="user_firstname">Nume</label>
    <input id="user_firstname" type="text" name="user_firstname" value="<?=$_SESSION['user_firstname']?>" />
    <? if (isset($errors['user_firstname'])): ?>
    <span class="error"><?= $errors['user_firstname']; ?></span>
<? endif; ?> 
+1
source
<input id="FirstName" name="FirstName" placeholder="First name" title="First Name" required="" tabindex="1" type="text" value="<?php if(isset($_POST['FirstName'])){ echo htmlentities($_POST['FirstName']);}?>"/>

This code is much easier to store form information after submitting the form.

0
source

All Articles