Daan
Daan

Reputation: 2799

Checking if username exists in Database jQuery

I want to check if the username is already taken, here is my script, which outputs "undefined". Can anyone help me, please? :)

This is in my jQuery - $("#registerusername").val() is the value of an input.

$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
    window.alert(data.exists);
    if(data.exists){
        window.alert("Name already found");
    }else{
        window.alert("Name NOT found");
    }
}, 'JSON');

This is in my checkregister.php

header('content-type: text/json');
if(!isset($_POST['username']))
exit;
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
echo json_encode(array('exists' => $query->rowCount() > 0));

Upvotes: 0

Views: 6698

Answers (2)

sravis
sravis

Reputation: 3680

Simple Example..

Jquery

var username  = $.trim($('#username').val());

if(username != '') {
$.ajax({
url : 'localhost/phpScript.php',
data : {username : username},
dataType : 'JSON',
type : 'POST',
cache : false,

success : function(result) {
if(result == '1') { alert('Username Found.'); }
else if(result == '0') { alert('Username Not Found!'); }
},

error : function(err) {
console.log(err);
}
});
}

PHP/MySQL (Make sure that you escape value for user input, Before giving it to MySql)

if(isset($_POST['username'])) {    
$username = $_POST['username'];
$sql = "SELECT username FROM users WHERE username = '".$username."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == '1') { 
echo '1'; 
} else { 
echo '0'; 
}
}

Upvotes: 0

DMortensen
DMortensen

Reputation: 141

First, You might want to strengthen your php against sql injection by 'sanitizing' the input.

Next why return JSON from the php? It would be much simpler to just return either true or false.

$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
if( $query->rowCount() > 0 ){
    echo 'true';
}
else{
    echo 'false';
}

Then in your javascript:

$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data);
if(data == 'true'){
    window.alert("Name already found");
}else{
    window.alert("Name NOT found");
}
});

edit--- You could also just return a boolean variable from php rather than a string, but either will work

Upvotes: 2

Related Questions