0

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";
}
?>
tech_boy
  • 195
  • 3
  • 13

2 Answers2

0

You do not need required="required", just required inside of your <input> tag.

Lati.Chris
  • 57
  • 6
0

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'

Community
  • 1
  • 1
Conor Reid
  • 95
  • 1
  • 7