jQuery Validate remote method usage to check if username already exists

Bishoy picture Bishoy · May 16, 2013 · Viewed 12.3k times · Source

I want to validate if username exists in database using jQuery.validate so here's what I have so far:

jQuery:

    $("#signupForm").validate({
        rules: {
            username: {
                required: true,
                minlength: 3,
                remote: "check-username.php"
                }
            },
        messages: {
            username:{
                remote: "This username is already taken! Try another."
            }
        }
  });

check-username.php:

<?php

require_once "./source/includes/data.php";
header('Content-type: application/json');

$name = mysql_real_escape_string($_POST['username']);

$check_for_username = mysql_query("SELECT username FROM mmh_user_info WHERE username='$name'");

if (mysql_num_rows($check_for_username) > 0) {
    $output = true;
} else {
    $output = false;
}
echo json_encode($output);
?>

This code always shows an error that the username is taken even if it's not.

I'm using jQuery Mobile 1.9.1

Thanks in advance.

Answer

Bishoy picture Bishoy · May 16, 2013

I've managed to get this to work by changing the PHP technique I was using, here's my PHP:

<?php
require_once "./source/includes/data.php";
header('Content-type: application/json');
$request = $_REQUEST['username'];

$query = mysql_query("SELECT * FROM mmh_user_info WHERE username ='$username'");
$result = mysql_num_rows($query);
if ($result == 0){
$valid = 'true';}
else{
$valid = 'false';
}
echo $valid;
?>

Thanks everyone here for your help :)