2016-07-31 83 views
0

我有一个form.php文件,当我提交表单时重定向到sendformdata.php文件。但是,我无法获得sendformdata.php文件在合适的字段未填写时在窗体内显示错误消息。

我简单地重定向到包含文件db_connect.php,它显示为空白页。我如何让页面留在form.php上并在html中显示错误消息?这是我目前sendformdata.php文件:PHP表单处理 - 使用javascript显示错误消息

<?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> 

在此先感谢您的帮助!

+0

您可以使用所需的标签来代替。 – bhansa

+0

我想在没有重定向的表单页面上显示消息。 – pcris

+0

是的,它不会重定向,直到你不填写表单。 – bhansa

回答

1

我建议您使用html5 required属性,这将强制用户输入数据。但请记住,用户可以绕过前端验证(通过检查元素),因此后端验证也是必要的。

使用所需的属性,如:

<input type="text" required /> 

你可以试试这个

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

让我知道如果这能解决你的问题

+0

使用必需的属性工作,但出于某种原因,使用此PHP代码手动执行它不起作用。 – pcris