簡體   English   中英

PHP表單處理-使用JavaScript顯示錯誤消息

[英]PHP form handling- display error message using javascript

我有一個form.php文件,當我提交表單時,該文件重定向到sendformdata.php文件。 但是,如果沒有填寫適當的字段,我無法獲取sendformdata.php文件在表單內顯示錯誤消息。

我只是被重定向到包含文件db_connect.php,該文件顯示為空白頁。 我如何才能使頁面停留在form.php上並在html中顯示錯誤消息? 這是我當前的sendformdata.php文件:

<?php

include_once('db_connect.php');



$lokotitle = $description = $category = $showyourname = $yourname = $lat = $lng = "";


if($_SERVER['REQUEST_METHOD'] == 'POST'){


  $lokotitle=$_POST['lokotitle'];
  $description=$_POST['description'];
  $category=$_POST['category'];
  $showyourname=$_POST['showyourname'];
  $yourname=$_POST['yourname'];
  $lat=$_POST['lat'];
  $lng=$_POST['lng'];




  // Validation will be added here   


  if(empty($lokotitle)) {
    $error_message = "Please input a Loko title.";
    ?><script>$('#notitle'.text($error_message));</script><?php
    exit;
  }


  if(!isset($error_message)){

    //Inserting record in table using INSERT query

    $insqDbtb="INSERT INTO `new`.`web_form`
    (`lokotitle`, `description`, `category`, `showyourname`, `yourname`, `lat`, `lng`) VALUES ('$lokotitle', '$description', '$category', '$showyourname', '$yourname', '$lat', '$lng')";
    mysqli_query($link,$insqDbtb) or die(mysqli_error($link));

    ?><script>window.location.href = "../index.php"; </script> <?php
    exit;
  }
}
?>

這是form.php的一部分,我試圖在其中顯示錯誤消息:

<form class="form-horizontal" role="form"  action="handleform/sendformdata.php" method="POST">
            <legend></legend>
            <div class="form-group">

                <label for="lokotitle" class="col-sm-2">Loko Title</label>
                <div class="col-sm-4">
                    <input type="text" class="form-control" name="lokotitle" id="lokotitle" placeholder="Title">
                    <span id="notitle"></span>
                </div>

先謝謝您的幫助!

我建議您同時使用html5 required屬性,這將強制用戶輸入數據。 但是請記住,用戶可以繞過前端驗證(通過inspect元素),因此后端驗證也是必要的。

使用必需的屬性,例如:

<input type="text" required />

你可以試試這個

  if(empty($lokotitle)) {
    $error_message = "Please input a Loko title.";
     echo "<script>
             document.getElementById('#notitle').value='".$error_message."';".
           "</script>";
    exit;
  }

讓我知道這是否解決了您的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM