简体   繁体   中英

Is there something wrong with my form?

I have my form working and all of the errors and everything works. But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information. Anyway to fix this?

I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form. Instead I have action=""

I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.

I tried using

<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">

and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?

Form code:

echo '    <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" /><br />
                                              Email: <input name="email" type="text" /><br />
                                              Phone Number: <input name="phone" type="text" /><br /><br />
                                              Comment: <br/>
                                              <textarea name="comment" rows="5" cols="30"></textarea><br /><br />
                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form></div>
                                            <div style="clear:both;"></div><br /><br />';

and the vaildator:

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

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
                                                }
                                                if ($errors) {
                                                    echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
                                                    echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
                                                } else {
                                                    mail( "email@hotmail.com", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'<span id="valid">Message has been sent</span><br/>';
                                                }
}

First: you cannot trust '.$_SERVER it can be modified. Be carefull with that!

Second: you could(should?) use a hidden field instead of specifing it in the action?

But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information. Anyway to fix this?

You could use ajax to fix it(I believe plain old HTML has this side-effect?).

A browser doesn't have to (p)refill a form. Some do for convenience, but you cannot rely on it.

In case you display the form again, you could set the values of the inputs like this:

$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';

Of course you should check and sanitize the POSTed data before including it in your HTML to not open up any XSS vulnerabilities.

If you want the form to submit to the same page, you don't need to set an action, it works without it as well. Also I'd suggest you to send the date in this way:

<input type="hidden" name="date" value="'.$date.'"/>

first, a few general changes:

change

<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">

to

<form method="post" action="'.$_SERVER["PHP_SELF"].'">
    <input type="hidden" name="data" value="'.$date.'" />

the answer to your original question:

set each input elements value attribute with $_POST['whatever'] if array_key_exists('whatever', $_POST);

For example: the name field

<input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />

A part from the fact that that validator and html code has some big issues inside and things i'd change, what you are asking is: How could i make that the form compiled doesn't remove all the text from my input tags after the refresh.

Basically not knowing anything about your project, where the strings submitted goes, if they are stored in a database or somewhere else, what does that page means inside your project context i cannot write a specific script that makes submitted string remembered in a future reload of the page, but to clarify some things:

If there is a form that is defined as <form></form> and is submitted with a <input type="submit"/> (which should be enough, without giving it a name name="submit" ) the page is refreshed and it does not automatically remember the input your previously submitted. To do that you have 2 choice:

  1. Use Ajax (check Jquery as good framework for ajax), which will allow you to submit forms without refreshing the page. I choose it as first way because it is over-used by everyone and it is going to became more and more used because it is new and it works smoothly.
  2. Make a php script that allows you to check if the input has already been submitted; in case the answer is true , then recover the values and get them in this way: <input type="text" value="<?php echo $value ?>"/> .

Also notice that you do not need of '.$_SERVER["PHP_SELF"].'?date='.$date.' since ?date='.$date.' is enough.

Browsers will not re-populate a form for you, especially when doing a POST. Since you're not building the form with fields filled out with value="" chunks, browsers will just render empty fields for you.

A very basic form handling script would look something like this:

<?php

if ($_SERVER['REQUEST_METHOD'] = 'POST') {
    # do this only if actually handling a POST
    $field1 = $_POST['field1'];
    $field2 = $_POSt['field2'];
    ...etc...

    if ($field1 = '...') {
       // validate $field1
    }
    if ($field2 = '...') {
       // validate $field2
    }
    ... etc...

    if (everything_ok) {
        // do whatever you want with the data. insert into database?
        redirect('elsewhere.php?status=success')
    } else {
       // handle error condition(s)
    }
} // if the script gets here, then the form has to be displayed

<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>

?>

Notice the use of htmlspecialchars() in the last bit, where form fields are being output. Consider the case where someone enters an html meta-character ( " , < , > ) into the field. If for whatever reason the form has to be displayed, these characters will be output into the html and "break" the form. And every browser will "break" differently. Some won't care, some (*cough*IE*cough*) will barf bits all over the floor. By using htmlspecialchars() , those metacharacters will be "escaped" so that they'll be displayed properly and not break the form.

As well, if you're going to be outputting large chunks of HTML, and possibly embedding PHP variables in them, you'd do well to read up on HEREDOC s. They're a special construct that act as a multi-line double-quoted string, but free you from having to do any quote escaping. They make for far more readable code, and you don't have to worry about choosing the right kind of quotes, or the right number of quotes, as you hop in/out of "string mode" to output variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM