0

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));
Daan
  • 2,680
  • 20
  • 39

2 Answers2

2

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

DMortensen
  • 141
  • 4
  • 1
    Better than sanitizing would be using prepared statements correctly. – Cᴏʀʏ May 08 '13 at 18:33
  • Thank you so much, it's now working, and I learned something new :) – Daan May 08 '13 at 18:35
  • @Cory very true, but an easy implementation of mysql_real_escape_string will do wonders http://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php – DMortensen May 08 '13 at 18:46
0

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'; 
}
}
sravis
  • 3,562
  • 6
  • 36
  • 73