I have small registration form which have following fields Idno, Name and Mobile No. I want to knew that How can I stop my form from submitting and generating an error if mobile no already existed in database . I tried with ajax but its not working Here is code of my simple form
<form method="POST" action="form1.php">
<div class="row"> <div class="col-lg-4"> <div class="form-group">
<label>ID No:</label> <input type="text" name= "idno" id= "idno" class="form-control" >
</div> </div>
<div class="col-lg-4"> <div class="form-group">
<label>Name:</label> <input type="text" name= "name" id= "name" class="form-control" Required >
</div> </div>
<div class="col-lg-4"> <div class="form-group">
<label>Mobile No:</label> <input type="text" data-inputmask="'mask': '0399-99999999'" name= "mob" id= "mob" class="form-control mobunique">
</div> </div></div>
<input type="submit" name="submit" id="submit" value="Submit">
here is ajax
<script type="text/javascript" src="/js/jquery.1.7.2.min.js"></script>
<script type="text/javascript" src="/js/jquery.validate.min.js"></script>
<script type="text/javascript">
jQuery.validator.addMethod("mobunique",function(value){
return eval($.ajax({
url: 'abc.php',
data: "mob="+value,
type: 'post',
async: false
}).responseText);
}, 'Mobile No exists, must be unique!');
$(function() {
// probably here is issue, i dont declare form name any where )
$('#form').validate();
});
</script>
here is abc.php which handle database for ajax
<?php
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$sth = $dbh->prepare("SELECT FROM person WHERE mob = ?");
$sth->execute(mysql_real_escape_string($_POST['mob']));
if ($sth->rowCount() > 0):
return true;
else:
return false;
endif;
?>
Here is backend
<?php
// getting all values from the HTML form
if(isset($_POST['submit']))
{
$idno = $_POST['idno'];
$name = $_POST['name'];
$mob = $_POST['mob'];
}
// database details
$host = "localhost";
$username = "root";
$password = "";
$dbname = "hmis";
// creating a connection
$con = mysqli_connect($host, $username, $password, $dbname);
// to ensure that the connection is made
if (!$con)
{
die("Connection failed!" . mysqli_connect_error());
}
// using sql to create a data entry query
$sql = "INSERT INTO person (idno, name, mob)
VALUES ('$idno', '$name', '$mob')";
// send query to the database to add values and confirm if successful
$rs = mysqli_query($con, $sql);
if($rs)
{
echo "";
}
// close connection
mysqli_close($con);
?>