简体   繁体   中英

Stay on same page using php without javascript

I need to validate a form using php. when i go to validate i need it to stay on same page if validation fails. is this possible. i know it can be done with the use of javascript but im trying to cater to those who turn javascript off.

不。如果您不愿意使用Javascript,则必须提交表单(并转到新页面)以进行验证。

Put all of the variables into strings, then use a post method to validate, and if there was a problem get the variables back out from the strings

$name = $_POST['name'];

<form action="validate.php" method="POST" value="$name">
<input type="text" id="name" /> 
</form>

PHP is server side code. In order to validate the page, you need to do a round trip to the server. If the form doesn't validate, then you can redirect them back to the same, page, along with some markup that explains the problem.

That said, only ~1% of people disable javascript, so I wouldn't worry about that.

Even if you do perform client side form validation in javascript, you should always validate server side as well.

While it is not possible to do without client side help it is possible to emulate the result by posting the for to the page that hosts the form.

if ($_SERVER["REQUEST_METHOD"] == "POST"){
       // validate your form and set placeholder variables for error messages.
       if(empty($_POST["username"])) $userError = "You must supply a username";

       // if the form is valid do a header redirect

       header("Location: http://mysite.com/myaccount/");

}
<form method='post'>
      <label for='username'>Username: </label>
      <input id='username' name='username' type='text' 
             value='<?= isset($_POST["username"])?$_POST["username"]:"" ?>'>
      <?= isset($userError)?$userError:"" ?>
</form>

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