Printing a PHP error inline instead of erasing the entire page

前端 未结 2 1505
感情败类
感情败类 2021-01-17 01:07

How can I make PHP print an error inline instead of changing the entire page?

I\'d like it to target #errors and fill that instead of changing everythi

相关标签:
2条回答
  • 2021-01-17 01:21

    Put the error in a variable where you do your logic and print its contents in #errors. For example:

    if (username_is_incorrect()) $error = 'Incorrect username or password.';
    

    And in the HTML

    <?php if (isset($error)):?><div id="errors"><?=$error?></div><?php endif;?>
    
    0 讨论(0)
  • 2021-01-17 01:30

    There are 2 ways of doing it.

    A real inline method is not entirely PHP-based, as it cannot be used without JavaScript and AJAX calls.
    Note the irritating disadvantage of this method: you will need to re-check every field again upon receiving form data finally.

    Another one will reload your page but it will be the same page with all the form fields, entered data and also freshly generated error messages. This is called POST/Redirect/GET pattern

    here is a short example

    <?  
    if ($_SERVER['REQUEST_METHOD']=='POST') {  
    
      $err = array();
      //performing all validations and raising corresponding errors
      if (empty($_POST['name']) $err[] = "Username field is required";  
      if (empty($_POST['text']) $err[] = "Comments field is required";  
    
      if (!$err) {  
        // if no errors - saving data 
        // and then redirect:
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
      }  else {
        // all field values should be escaped according to HTML standard
        foreach ($_POST as $key => $val) {
          $form[$key] = htmlspecialchars($val);
        }
    } else {
      $form['name'] = $form['comments'] = '';  
    }
    include 'form.tpl.php';
    ?>  
    

    while in the form.tpl.php file you have your form fields, entered values and conditional output of error messages

    <? if ($err): ?>
      <? foreach($err as $e): ?>
    <div class="err"><?=$e?></div>
      <? endforeach ?>
    <? endif ?>
    <form>
      <input type="text" name="name" value="<?=$form['name']?>">
      <textarea name="comments"><?=$form['comments']?></textarea>
      <input type="submit">
    </form>
    
    0 讨论(0)
提交回复
热议问题