简体   繁体   中英

Required fields in form doesn't work

I am trying to make a subscription form with only input as email-id. First, I made using html and php wherein it stored the email-id and also it was checking for required parameters like '@' and '.' etc.

Like email-id ="d" showed error

But once i added the ajax, it took care about if email-id exist in the table than showed already subscribed but the feature about require parameter stopped working.

Like email-id= "d" also worked

Code is as follows :

index.html

<form  class="searchform" method ="post" >
        <input id="email" type="email" name="email" required="required" />
        <button id="submit" type="submit"> </button>
</form>

Ajax file : script.js

$(document).ready(function(){
$("#submit").click(function(){

var email = $("#email").val();

var dataString =  '&email='+ email ;
if(email=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "email.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});

Php database code : email.php

<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$username = "myusername";
$password = "mypassword";
$hostname = "localhost"; 
$dbname= "mydbname";

//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password,$dbname);
if(! $dbhandle )
{
  die('Could not connect: ' . mysql_error());
}
$email=$_POST['email'];

$sql = "INSERT INTO  email_table". "(email)". "VALUES ('$email')";

if (mysqli_query($dbhandle, $sql)) {
    echo "You have subscribed successfully";
} else {
    echo "You have already been subscribed";
}
?>

您不需要required="required" ,只required<input>标记内部。

jQuery/JS does not know anything about the HTML form validation. Therefore you'll need to validate it with jQuery/JS like:

$('#submit').click(function(){
    if($("form")[0].checkValidity()) {
        //your form execution code
    }else console.log("invalid form");
});

HTML5 validation before ajax submit

You could also handle the response from a PHP file using AJAX to check if it was empty.

$.ajax({
        url: url,
        type: type,
        data: data,
        success: function(response) {
            $(".class").html(response);
        }
    });

the PHP file could be:

if ($_POST['email'] == "") {
   echo 'Please enter an email';
}

"Please enter an email" would be the error response and it would be placed inside whatever has the class='class'

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