aeonxs11 aeonxs11 - 1 month ago 15
MySQL Question

JQuery Duplicate Email Validation

I have just started studying programming and I've been stuck for hours in this problem. I have a sign up form which asks for email and it should check the mysql database if the email is already registered. I am currently trying to use the remote method from the Jquery validator plugin but I can't seem to make it work.

emailcheck.php

<?php
include_once 'dbconnect.php';
$email = $_POST['CusEadd'];
$query = "SELECT CusEadd FROM customer WHERE CusEadd='$email'";
$result = mysql_query($query);
$count = mysql_num_rows($result);

if($count>0){
echo json_encode(FALSE);
}
else {
echo json_encode(TRUE);
}

?>


form-validation.js

CusEadd: {
required:true,
email:true,
remote:"emailcheck.php"
}

Answer

The documentation for jQuery Validate states that

The serverside resource is called via jQuery.ajax (XMLHttpRequest) and gets a key/value pair corresponding to the name of the validated element and its value as a GET parameter.

The serverside response must be a JSON string that must be "true" for valid elements, and can be "false", undefined, or null for invalid elements

You're checking for $_POST['CusEadd'], and assuming you have an element with that name, you still have to specify POST as a method

CusEadd: {  
    required:true,
    email:true,
    remote: {
        url  : "emailcheck.php",
        type : "POST"
    }
}

Also, you want to return the string "true", not PHP booleans, which usually converts to numbers

if($count>0){
    echo json_encode("false");
}
else {
    echo json_encode("true");
}

And do not use mysql_* in production code, your code is open to SQL attacks by simply passing something like 'OR 1=1 to the POST variable

Comments