0

Hello,

So I have a PHP page where I can enter my name, address, phone #, etc. I have some of these fields designed to be required information. If I do not enter something in the required fields, then information I have in other fields are lost when I submit the information.
For instance let's say "Name", "Address", and "Phone number" are set as required fields, If I were to enter my name and address, but not my phone number and submitted the information, the page would refresh and display "Each field is required", however the fields marked name and address would be empty. How do I prevent that from happening?

7
Contributors
8
Replies
40
Views
4 Years
Discussion Span
Last Post by diafol
0

I don't have an exact answer my friend but I might be able to push your search into the right direction. Usually this type of behaviour is down to the clients browser, therefore I would suggest looking at JavaScript which is all executed client side. Perhaps looking into the onkeyup event to detect and collect user data and then store the data in a cookie? It's a rough answer and maybe someone here can really push you in the best direction - that's just my input.

I pulled this answer from a user called arthurr on StackOverflow:

I had similar issue at one of my project so I wrote some js to handle this using cookies. First I found two simple functions to set and get cookies values:

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
  {
  c_start = c_value.indexOf(c_name + "=");
  }
if (c_start == -1)
  {
  c_value = null;
  }
else
  {
  c_start = c_value.indexOf("=", c_start) + 1;
  var c_end = c_value.indexOf(";", c_start);
  if (c_end == -1)
  {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}

Than I wrote two other functions to set and get input values:

function saveValue(input) {
    var name = input.attr('name');
    var value = input.val();
    setCookie(name,value);
}

function getValue(input) {
    var name = input.attr('name');
    var value = getCookie(name);
    if(value != null && value != "" ) {
        return value;
    }
}

And using jQuery I save user's input value to session cookie

$('input[type=text]').each(function(){
        var value = getValue($(this));
        $(this).val(value);
    }).on('blur', function(){
        if($(this).val() != '' ) {
            saveValue($(this));
        }
    });

I hope it'll help ;)

Good luck!

Edited by mmcdonald

0
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>
<input type='text' name='firstname' value='<?php if(isset($_POST['firstname'])){echo $_POST['firstname'];} ?>'><label for='firstname'>First Name</label>
0

Why not using directly sessions ? On submit, save each value of the inputs in a different session. If a field is empty, we can redirect the user to the form - but this time we can auto-complete the other inputs using the data provided last time (which was stored in the sessions).

Probably something like this (not tested) :

<?php if (isset($_SESSION["name"]) && !empty($_SESSION["name"])) : ?>

    <input type=text value="<?php echo htmlspecialchars($_SESSION["name"]); ?>"/>

<?php else : ?>

    <input type=text value="Please complete this field."/>

<?php endif; ?>

Edited by TheApex

0

Blikin' hell I totally misunderstood the question haha, sorry!

On form submission you could create a session for each of the fields before processing and then simply unset/destroy the sessions at the end of processing.

I.E:

if(isset($_POST['forum_submit'])){

    //Create session for each field
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['firstname'] = $_POST['firstname'];
    // and so forth...

{

and then for each field:

<input name="username" type="text" value="<?php if(isset($_SESSION['username'])){echo $_SESSION['username'];} ?>">

Therefore if a session exists that holds form data it'll be entered as input field values.

Edited by mmcdonald

0

For instance let's say "Name", "Address", and "Phone number" are set as required fields, If I were to enter my name and address, but not my phone number and submitted the information, the page would refresh and display "Each field is required", however the fields marked name and address would be empty. How do I prevent that from happening?

I'm not sure if I missed something here, but I dont see any recommendations for validating client side before allowing a post back to occur. Of course I understand that you should also validate server-side to make sure that the client side validation wasnt bypassed, but why bother making a trip to the server if you can check these values client-side first?

0

I agree with jorgeM

an example:

<html>
<head>
<script>
function validate()
{
if (document.forms["frm"]["name"].value)
    {
    alert("Welcome " + document.forms["frm"]["name"].value + "!")
    return true; // form will submit
    }
else 
    {
    alert("no user");
    return false; // form will not submit       
    }
}
</script>
</head>
<body>

What is your name?<br>
<form name="frm" action="submit.htm" onsubmit="return validate();">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>

</body>
</html> 

Edited by pzuurveen

0

Your approach needs to be two-fold, as mentioned by contributors thus far.

  1. Enable users to get immediate feedback from client-side validation (javascript), so that they do not send the form with invalid data in the first place. Some will not have js enabled of course. There are plenty of examples to be had online.

  2. Your server-side validation routine needs to capture all the fields and place them into a session array variable which can be returned to the form page. This variable should then be killed once the info is extracted from it. Repopulate the various form fields. You can use additional info from the validation, e.g. an error variable or item in the session to place an error message (inline or in a section) on the form page.

Example PHP (quick and dirty)

session_start();

$formExpectedData = array(
    'key1' => array('required' => true, 'type' => 'int', min => 10, max => 25, 'err_msg' => 'Your value for key1 must be between 10 and 25'),
    'key2' => array('required' => false, 'type' => 'string', min=>0, max=>32, 'err_msg' => 'If you provide key2, it must have a maximum of 32 characters...'),
    //...etc...//  
);

if(isset(!$_POST['some_field']))
{
    $result = array();
    $error = false;
    foreach($_POST as $key=>$value)
    {
        $result[$key] = validate($key, $value, $formExpectedData[$key]);
        if($result[$key]['error']) $error = true;
    }
    if($error)
    {
        $_SESSION['form_error'] = $result;
        header('Location: formpage.php');
        exit;
    }
}

The validate function checks each item value against expected/allowed data. That's a very rough example. You'll have a much better validation array structure I'm sure.

Edited by diafol

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.