简体   繁体   中英

PHP form handling- display error message using javascript

I have a form.php file that redirects to a sendformdata.php file when I submit the form. However, I can't get the sendformdata.php file to display an error message within the form when the proper fields aren't filled out.

I am simply redirected to the include file, db_connect.php, which shows up as a blank page. How can I get the page to stay on form.php and display an error message in html? This is my current sendformdata.php file:

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

This is a section of form.php that I am trying to display an error message in:

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

Thanks in advance for the help!

I recommend you to use both html5 required attribute which will force the user to enter the data. But remember the user can bypass front end validation (by means of inspect element), hence back end validation is also necessary.

Use required attribute like:

<input type="text" required />

You can try this

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

Let me know if this solves your problem

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