2

I'm creating a registration form. The user enters the username and password, and presses submit, and the form is submitted using POST. HTML :

<link href="Styles/RegisterStyles.css" rel="stylesheet" type="text/css" />
<form id="frmRegister" method="post" action="register.php">
  <h1>Register</h1>
    <table width="100%">
      <tr>
        <td width="16%"><label class="alignRight"> Username: </label></td>
        <td width="84%"><input name="txtUsername" type="text" maxlength="40" /></td>
      </tr>

      <tr>
        <td width="16%"><label class="alignRight"> Password: </label></td>
        <td width="84%"><input name="txtPassword" type="text" maxlength="40" /></td>
      </tr>

      <tr>
        <td width="16%">&nbsp;</td>
        <td width="84%"><input name="Submit" class="submitButton" type="submit" /></td>        
      </tr>

    </table>
</form>
</html>

PHP:

$username = $_POST["txtUsername"];
$password = $_POST["txtPassword"];
//Code to connect to database

function doesUsernameExist($username)
{
    //return true if username exists or false otherwise
}

Now, in PHP, I run a query to check if the username exists in the database. If the username already exists, how can I notify the user without navigating to another page and causing the "username" and "password" fields to be reset to blank?

Some registration forms have a really neat Javascript that checks if the username exists each time you press a key on the keyboard. Any ideas on how this could be implemented? It's difficult ( and bad practice ) to connect to a database using JavaScript from what I can gather.

David
  • 15,652
  • 26
  • 115
  • 156
  • Are you using jQuery? Can you post your HTML, also? – Steven Moseley Dec 05 '12 at 18:56
  • One way I can think of is that after you have, say 3 characters of their username, you generate a list of all the already taken usernames and give that to the JS. From there on, let the JS check if the selected username is already in the list or not – Some Guy Dec 05 '12 at 18:57
  • 1
    Use AJAX. It is basically a 'normal' request to a server, only without refreshing the page. Instead, the request is executed by Javascript in the background. The request can simply be handled by a PHP script. The response of that script can be processed by Javascript. AJAX is really simple with JQuery, although there are plenty of snippets that how to use AJAX without JQuery. – GolezTrol Dec 05 '12 at 18:57
  • No jQuery unfortunately. I'll post HTML soon. – David Dec 05 '12 at 18:57
  • 2
    FYI, this would be best accomplished with an AJAX call in the onkeypress or onblur event of the input. – Steven Moseley Dec 05 '12 at 18:57
  • The javascript initiates an asynchronous call (AJAX) to the server, which calls the database to see if the name is available. The database returns data to the server which returns it to the client. – Shmiddty Dec 05 '12 at 18:57
  • instead of checking for the username on each key, check it when the username field loses focus. See if this helps: http://www.w3schools.com/ajax/ajax_aspphp.asp – greener Dec 05 '12 at 18:57
  • You could always use the http://jquery.malsup.com/form/ jQuery plugin. Work likes a charm for me – Stephen Cioffi Dec 05 '12 at 18:57
  • @AmaanCheval returning a full list of users is not a good practice, it exposes your users – greener Dec 05 '12 at 19:00
  • David, I'm the only one who asked you about your environment before writing an answer, and took the time to post an answer that could work for you... can you please in return take the time to review my answer and respond? Thanks. – Steven Moseley Dec 05 '12 at 19:11
  • I will of course, I'm still reading the questions. I always accept answers. – David Dec 05 '12 at 19:14

4 Answers4

3

I use jQuery to do something like this.

in the html

<input type="text" name="username" onBlur="checkUsername(this)">

in the javascript something like this

function checkUsername(v){
    $.post("phppage.php",{
        valToBeChecked:v
    },function(d){
        if($.trim(d)==true){
            // php page returned true
        }else{
            // php page returned false
        }
    });
}

do note this is only an example, I think I got the syntax right tho.

NappingRabbit
  • 1,888
  • 1
  • 13
  • 18
  • 1
    He said he doesn't use jQuery – Steven Moseley Dec 05 '12 at 19:01
  • yeh the question was changed before I was done typing, I didnt notice. should I delete the answer? it is still a valid solution. – NappingRabbit Dec 05 '12 at 19:02
  • Ok, but even so - I'm a bit curious. If I use $.post("phppage.php", it won't refresh the page but just post it? – David Dec 05 '12 at 19:02
  • Don't delete the answer, it's okay – David Dec 05 '12 at 19:03
  • `v` is the name of the variable that the value will be sent as, so in PHP just reference the sent data by: `$_POST['v']`. `d` is the content of the php page, or the returned data from the request. Your PHP page should echo or return true, or false after checking the username. – Felix Guo Dec 05 '12 at 19:08
  • Thank you for your answer by the way, it made be reconsider using jQuery. Very clean and intuitive. I won't accept it but the next best thing is a +1 :) – David Dec 05 '12 at 19:18
1

My solution to this would be to utilize AJAX.

On submission of your form, make an AJAX call to a page that will evaluate the data that has been input into the form, and return information regarding whether or not it was validated.

After you get back some information from that AJAX call, determine whether or not to submit the form again, but this time to a page that will absorb the data into the database.

It's one solution; and as an AJAX newbie I'd say there are probably better ones, but it might work for you.

DigitalJedi805
  • 1,486
  • 4
  • 16
  • 41
1

This will do an AJAX check on blur of the input without jQuery.

Edit: I want to clarify that I don't suggest this approach, and much prefer the use of jQuery (or other similar JS framework) for AJAX. However, I understand that not everyone has the luxury of specifying the technologies they use, and so here's the answer to your request! :)

<input id="txtUsername" name="txtUsername" />
<script type="text/javascript">
    window.onload = function() {
        document.getElementById('txtUsername').onblur = function(e) {
            // Get the username entered
            var el = e.target;
            var username = el.value;

            // Create an XHR
            var xhr = null;
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } else {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }

            // AJAX call to the server
            request.open('GET', '/check_username.php?username=' + username, false);
            xhr.onload = function(e) {
                var json = eval(xhr.responseText);
                if (json.exists) {
                   window.alert('That username exists already.');
                }
            }
            xhr.send();
        }
    }
</script>

user_exists.php

$username = isset($_GET['username']) ? $_GET['username'] : '';
$username = mysqli_real_escape_string($username);

$sql = "SELECT COUNT(*) > 0 AS user_found
        FROM users
        WHERE username = '{$username}'";

$result = mysqli_query($sql);

$exists = false;
if ($row = mysqli_fetch_assoc($result)) {
    $exists = $row['user_found'] ? true : false;
}

echo json_encode(array('exists' => $exists));
Steven Moseley
  • 15,871
  • 4
  • 39
  • 50
  • Good example, but I thought there would be needed some browser dependent stuff? – GolezTrol Dec 05 '12 at 19:02
  • Thanks! I'll try it out, I've only heard of AJAX, never used it so far. – David Dec 05 '12 at 19:11
  • Ok, well it's complicated outside a framework like jQuery. The above may not work 100% for all browsers. – Steven Moseley Dec 05 '12 at 19:12
  • this illustrates the beauty of jQuery in two ways. much less code for similar result, and cross browser considerations need not be considered (as avidly). good job btw, I would have to look it up to write raw javascript these days for sure. – NappingRabbit Dec 05 '12 at 20:35
  • 1
    @NappingRabbit - I totally agree with you. I would never do this (or suggest it) without jQuery or other similar framework. Same goes for DOM manipulation. But not everyone has the luxury of specifying the technologies they use. – Steven Moseley Dec 05 '12 at 20:38
  • Well, 'much less code'... You will need the JQuery library which contains a lot of code in itself. If you only need it for AJAX, you can easily download a lighter library, or find a specific function. After all, this answer shows how little code is actually involved in performing an AJAX request. You can easily wrap this in a function of your own. – GolezTrol Dec 05 '12 at 23:39
0

A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You don't want to pass a blank value, this is where you would put your username and password to deliver to FILE2.php. In your case, the line would look like this:

data: 'username='+username+'&password='+password,

In the FILE2.php example, you would retrieve those values like this:

$uname = $_POST['username'];
$pword = $_POST['password'];

Then do your MySQL lookup and return the values thus:

echo 1;

This would deliver a 1 to the success function in FILE1.php, and it would be stored in the variable called "data". Therefore, the alert(data) line in the success function would alert the number one.

Here is another good example to review.

The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.

The secondary PHP file returns a response (whatever you choose to send) and that appears in the Success: section of your AJAX call.

The jQuery/AJAX is JavaScript, so you have two options: you can place it within <script type="text/javascript"></script> tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?> at the bottom of your PHP document.

halfer
  • 19,824
  • 17
  • 99
  • 186
crashwap
  • 2,846
  • 3
  • 28
  • 62