Ash23
Ash23

Reputation: 37

php js username live check

I'm working on a piece of my website application to give a life feedback whether a username is available or taken. I got to a dead end, and I'm wondering if I can get some help. Here is my js code:

$('#username').keyup(function() {


 var username = $(this).val();

$('#username_status').text('Searching...');

if (username !='') {
    $.post('username_check.php', { username: username}, function(data) {
        $('#username_status').text(data);
    });
} else{
    $('#username_status').text('');
}});

here is my php code:

<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>

<?php
  if (isset($_POST['username'])) {
  $username = mysqli_real_escape_string($_POST['username']);
  if (!empty($username)){
    $username_query = mysqli_query($con"SELECT COUNT('id') FROM 'attendant' WHERE 'username'='$username'");
    $username_result = mysqli_result($username_query, 0);

    if ($username_result == 0) {
      echo 'Username availabe!';
    } else if ($username_result == 1){
      echo 'sorry, that username is taken.';
    }
  }
}
 ?>

Upvotes: 0

Views: 86

Answers (1)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

There are a few things wrong with your code, as I've already outlined in a comment earlier, so I decided to post an answer in that regard, should you not have seen it. Many times, comments are unseen, and/or misunderstood.

  • The (something) missing comma between $con and "SELECT mysqli_query($con"SELECT which should read as mysqli_query($con,"SELECT
  • mysqli_real_escape_string() requires a DB connection be passed as the first parameter.

Which should read as:

$username = mysqli_real_escape_string($con, $_POST['username']);
  • Using the wrong identifiers for your table and columns, being quotes '

in:

SELECT COUNT('id') FROM 'attendant' WHERE 'username'
             ^  ^       ^         ^       ^        ^

Either remove the quotes:

SELECT COUNT(id) FROM attendant WHERE username

or replace them with backticks:

SELECT COUNT(`id`) FROM `attendant` WHERE `username`

Debugging/troubleshooting:

When writing code add or die(mysqli_error($con)) to mysqli_query()
and use error reporting.

Sidenote: Error reporting should only be done in staging, and never production.


An insight:

  • Make sure that your form's elements corresponds to your variables.

  • Plus, make sure your DB connection is mysqli_ and not mysql_ or PDO. Many times, people mix those different APIs together; they do not intermix. I say this because I don't know which API you are using to connect with; there is no indication of it in your code/question.


Special note:

Upvotes: 1

Related Questions