I'm trying to do a username availability check on my website, i.e during registration, it checks if a username is taken or still available. However when i execute i get no result at all,nothing happens. My code:

Registration page

*register.php: *

//this form posts to the same script. 
//In this script, i insert the registration data into database, including the username
<form action="register_page.php" method="post">
<label>Username:
<input type="text"  name="newusername" id="newusername" required/>
<span id="user-result"></span>
</label>

//other form entries
</form>

still in register.php; in the head tag i have the following jquery

<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#username").keyup(function (e) {

        //removes spaces from username
        $(this).val($(this).val().replace(/\s/g, ''));

        var username = $(this).val();
        if(username.length < 2){$("#user-result").html('');return;}

        if(username.length >= 3){
            $("#user-result").html('Checking...');
            $.post('check_username.php', {'username':username}, function(data) {
              $("#user-result").html(data);
            });
        }
    }); 
});
</script>

and then i have another php script were the check is performed

check_usename.php:

<?php
$username = "root";
    $password = "root";
    $database = "db";
    $server = "localhost";

//check we have username post var
if(isset($_POST["newusername"]))
{
    //check if its ajax request, exit script if its not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die();
    }

    $db_handler = mysql_connect($server, $username, $password);
    $db_found = mysql_select_db($database,$db_handler);


    //trim and lowercase username
    $username =  strtolower(trim($_POST["newusername"])); 

    //sanitize username
    $username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);

    //check username in db
    $results = mysql_query("SELECT id FROM tbl_user WHERE username='$username'");

    //return total count
    $username_exist = mysql_num_rows($results); //total records

    //if value is more than 0, username is not available
    if($username_exist > 0) {
        die('<span>Username is taken</span>');
    }else{
        die('<span>Username is available</span>');
    }

    //close db connection
    mysql_close($db_handler);
}
?>

Thanks in advance.

Im not a PHP expert, but I dont see where you are returning the results as HTML.

Im assuming your intention is to return the data as HTML based on line 15 in your jQuery code... $("#user-result").html(data);

yes you're right.. the data should be returned based on line 15. is it wrong..?

Member Avatar for diafol

I dont see where you are returning the results as HTML.

I think that would be lines 33 and 35.

However, I believe an echo or print would suffice just as well.

comment out the ajaxcheck conditional (11-13) and run it as a standalone php page to see if you get any output.
On line 6 insert ...

$_POST["newusername"] = 'diafol'; //or names present or absent from table

For testing purposes.

If it's OK - then it may be due to the conditional always returning false.

Yes I see it as well also thanks to diafol. On 33/35 you would echo out something so that HTML is retrieved by your AJAX call.

Test you PHP page by calling it with a browser to make sure you are seeing output.

Thanks. The PHP page check_username.php displays the message "username is available" when i set $_POST["newusername"] = 'diafol';and comment out lines 11-13 as you mentioned. However, when i enter a username in the textbox in register.php the message (username is available or unavailable) is still not displayed beside the username textbox where it is supposed to be.

Member Avatar for diafol

OK, comment out the whole page and just have

echo "checkpage";

at the bottom

$.post('check_username.php', {'username':username}, function(data) {
    alert(data);
});

Or keep it as it was and see if the user_result shows checkpage. We need to be sure that ajax call is reaching your php file.

Please i'm not sure i understand your entire response properly. What page should i comment out entirely? Can you please clarify it a bit..Thanks

What diafol is recommending is that you perform a simple test. On your PHP page, comment all of the logic and simply have the page echo "checkpage". what this means is that any time you open that page, that is all you should see on the screen. You've set aside all of the logic on the page because he is suggesting you test your ajax call with that simple response from the PHP page.

What this code does in your script is call the page via post and even though its sending data, the point of interest is to see if you are receiving data back. You should get "checkpage" back. The alert function is simply displaying the html your ajax call got back.

$.post('check_username.php', {'username':username}, function(data) {
    alert(data);
});

If you get the data back, your ajax call is correct.. then you go back to your PHP page and start uncommenting your code, checking your progress until it breaks again. Then continue fixing your code in chunks until its all working.

commented: thanks Jorge - well explained +14

Okay got it. There's still no output though. I guess this means the ajax call is incorrect..? I can't see how.

Member Avatar for diafol

if you're using Chrome have a look at : Inspect Element > Console (other browsers have their equivalents) to see if there's a javascript error upstream that stops execution of the ajax part.

Ensure that the 'check_username.php' file is in the same directory as your page.

Also have a look at the error (.fail) syntax for jQuery ajax calls...

var ajax = $.post('check_username.php', {'username': username}, function(data) {
   $("#user-result").html(data);
})
  .fail(function(jqXHR, textStatus) {
    alert( "Error: " + textStatus );
  });

there's still no output though

So to be clear... when you visit the php page directly with the browser, you see the output on the screen, but via Ajax, nothing? If so, follow diafol's recommendation and report back.

If you visit the page directly and still no output, fix that first before you work on the ajax component.

Member Avatar for iamthwee

I bet he's not loading the jquery library, it's probably in a different directory.

have a look at : Inspect Element > Console

It worked!!.. It wasn't reading the jquery file though in the same directory. I was able to see that by doing **Inspect Element > Console ** as diafol recommended. I changed it from

<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>

to

<script type="text/javascript" src="jquery-1.9.0.min.js"></script>

and it worked.
Thank you diafol and JorgeM for your help. iamthwee; thanks for your contribution too.

Member Avatar for iamthwee

I know this thread is solved but for future reference it's the norm to load the jquery library from google sources.

Yes you need an internet connection, but I'm assuming this is going to go live on your domain at some point. It also has the advantage that most users have this already cached from using other sites so it saves a bit of bandwidth too.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.