I'm trying to check whether the email user just entered is in the database or not and display message.its working fine. but when I delete entered value and focus out then other option is displayed. But I don't want to display neither.Here is my codes-ajax
<script>
$(document).ready(function(){
$("#email").focusout(function(){
var emailVal = $('#email').val();
$.ajax({
type: 'post',
url: 'check_email.php',
data: {
myparam:emailVal //set it with a parameter name
},
success: function( data ) {
alert(data);
if(data==1){
document.getElementById('email_check').innerHTML="<p style='color:red;'>The email you have entered is already exist!</p>";
}
if(data==0){
document.getElementById('email_check').innerHTML="<p style='color:green;'>The email you have entered is available!</p>";}
}
});
});
});
</script>
Here is my check_email.php file,
<?php
require_once("connnection.php");
$con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['myparam'])){
$email=mysqli_real_escape_string($con,$_POST['myparam']);
$sql = "SELECT * FROM user WHERE email='$email'";
$select=mysqli_query($con,$sql) or die("fail");
$row = mysqli_num_rows($select);
if ($row >0) {
echo 1;
}else {
echo 0;
}
else
echo "post error";
After delete entered value and focus out (click another place), the following happens, using alert(data) I got 0 as data from server. How could this happened. If there is no value in the text field, how it entered in to sql query segment in php file. Is there any default value or something which pass behind the scene? please explain?
If there is no value in the text field it will send
myparam: ""
That will then check if there is an email address with "" and that will return 0.
Just check if the text field is empty before doing the php call to get around this.
Just check the value of emailVal
either it exist or not. Try this
$(document).ready(function(){
$("#email").focusout(function(){
var emailVal = $('#email').val();
if($.trim(emailVal)){ //Added the new condition
$.ajax({
type: 'post',
url: 'check_email.php',
data: {
myparam:emailVal //set it with a parameter name
},
success: function( data ) {
alert(data);
if(data==1){
document.getElementById('email_check').innerHTML="<p style='color:red;'>The email you have entered is already exist!</p>";
}
if(data==0){
document.getElementById('email_check').innerHTML="<p style='color:green;'>The email you have entered is available!</p>";}
}
});
}else{ //If empty then nothing will be shown
$('#email_check').html('');
}
});
});