bɪˈɡɪnə
bɪˈɡɪnə

Reputation: 1085

Issues checking if username exists using ajax php

I have a problem and a question for the code below.

  1. The code below performs a live check if username already exists in database. Now when I enter username manually it all works fine with giving live success or error message as the case is but when after typing 1 or 2 characters I choose username from autofill options given by browser It doesn't give any success or error message instead keeps showing Enter 3 to 11 characters which is initial message for username requirements. Can't figure out why it doesn't work when username is selected from autofill options.

index.php

<script type="text/javascript">
$(document).ready(function(){
$('#un').keyup(function(){
    var username = $(this).val();
    var Result = $('#result'); 
    if(username.length > 2 || username.length > 11) { // if greater than 2 (minimum 3)
        Result.html('./img/loadgreen.gif');
        var dataPass = 'action=availability&username='+username;
        $.ajax({ // Send the username val to available.php
        type : 'POST',
        data : dataPass,
        url  : 'available.php',
        success: function(responseText){ // Get the result
            if(responseText == 0){
                Result.html('<span class="success">Available</span>');
            }
            else if(responseText > 0){
                Result.html('<span class="error">Unavailable</span>');
            }
            else{
                alert('Problem with sql query');
            }
        }
        });
    }else{
        Result.html('Enter 3 to 11 characters');
    }
    if(username.length == 0) {
        Result.html('');
    }
 });
});
</script>

<table>
<tr>
<td>
<input type="text" name="username" id="un"  placeholder="Username" class="username" />
</td>
<td class="result" id="result"></td>
</tr>
</table>

available.php

<?php
include ( "./inc/connect.php" );
if(isset($_POST['action']) && $_POST['action'] == 'availability')
{
   $username = $_POST['username'];
   $que=$db->prepare("SELECT username FROM users WHERE username=:username");
   $que->execute(array(':username'=>$username));
   $count = $que->rowCount();
   echo $count;
}
?>
  1. Now my question is how to secure POST on available.php lot of people tell you need to sanitize or escape every POST and GET data. So what works best with PDO. Also heard escaping doesn't works with PDO may be I am wrong?

Upvotes: 1

Views: 721

Answers (1)

McCuz
McCuz

Reputation: 227

  1. try jquery .change() instead of .keyup()

Upvotes: 1

Related Questions