Talking to PHP with jQuery
JQuery supports a method called
$.postwhich facilitates the transmission of form values to the Web server. We can use the
$.postmethod to send the desired username to a PHP script, which will subsequently query the
accountstable to determine whether the username has already been chosen by another user. Let’s start with the revised jQuery code:
$.post()method sends a POST request to
validate.php(which in this example resides in the same directory as the registration form; you’ll use a URL if the validator resides elsewhere), passing along a POST variable named
usernamewhich contains the current value of the username field. The returned
responsevalue is examined to determine whether the username is available, and a DIV named
existsis updated accordingly. Therefore you’ll need to add the DIV to the form, presumably in the immediate vicinity of the username field:
<input type="text" id="username" name="username" size="25" /> <span id="exists"></span>
The PHP script (
validate.php) used to determine whether the username exists is presented next. As you can see this is a straightforward script, using the MySQLi extension in conjunction with prepared statements to determine whether the provided username exists. If no rows are found, zero is returned, otherwise one is returned.
<?php // jQuery's $.post() sends parameters using the POST method $username = $_POST['username']; // Connect to the MySQL server $db = new mysqli("localhost", "webuser", "secret", "website"); // Create a prepared statement which queries the table for a username $stmt = $db->prepare("SELECT id FROM accounts WHERE username = ?"); // Bind the $username variable to the placeholder $stmt->bind_param('s', $username); // Execute the prepared statement $stmt->execute(); // You *must* store the result in order to determine the row count $stmt->store_result(); // How many rows were returned? echo $stmt->num_rows; ?>
The beauty of this approach is the ability to decorate the response in any way you see fit. While this example simply updated a DIV with a simple message, you could use jQuery’s other DOM manipulation capabilities to add or change the DIV’s CSS attributes, cause the form field to turn red or green depending on the outcome, or implement any other visual cue which you think will help the user to effortlessly complete the registration process.
Do you use Ajax to simplify the account registration process? Share your tips and tricks in the comments!