Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP keep form info after submit form failed

Tags:

forms

php

submit

Hello I am building a form in a mvc system view, and i want that all the inserted values will be kept,in case of form submit failure. How can this be done: i tried like (example for a 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 post action is done).

what is the simplest way to do this? any ideas?

thank you

like image 360
dana Avatar asked May 10 '26 02:05

dana


2 Answers

Just loop through the DOM in javascript and put the PHP $_POST data into the input.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>
like image 157
john ktejik Avatar answered May 12 '26 15:05

john ktejik


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 the $_POST["user_firstmane"] should be $_POST["user_firstname"] :)

like image 35
Gabriel Spiteri Avatar answered May 12 '26 17:05

Gabriel Spiteri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!