Right, so dynamic register thing with ajax/jquery
There are 2 files: register.php and register_verify.php
register.php holds the frontend stuff, what the user sees, and all the ajax code. register_verify.php holds the database queries and return data.
I'm gunna reference these by line numbers so I suggest you stick it into something other than notepad, I like Crimson Editor myself, but anything with numbering will do.
This code will check to see if the username and email the user has entered is available or not, and if the password and password confirm fields match, outputting the response to the user without having to refresh the page.
register.php
<?php
session_start();
require_once("connection/mycon.php");
mysql_select_db($database_db, $mycon);
if ($_POST['registerSubmitted'] == 1)
{
$username = mysql_real_escape_string(strip_tags($_POST['username']));
$email = mysql_real_escape_string(strip_tags($_POST['email']));
$password = mysql_real_escape_string(strip_tags($_POST['password']));
$password_confirm = mysql_real_escape_string(strip_tags($_POST['password_confirm']));
$query_checkusername = "SELECT * FROM u_user WHERE username='$username'";
$run_checkusername = mysql_query($query_checkusername, $mycon);
$num_checkusername = mysql_num_rows($run_checkusername);
$query_checkemail = "SELECT * FROM u_user WHERE email='$email'";
$run_checkemail = mysql_query($query_checkemail, $mycon);
$num_checkemail = mysql_num_rows($run_checkemail);
if ($username == "") { $error = 1; $username_error = 1; }
if ($num_checkusername > 0) { $error = 1; $username_error = 1; }
if ($email == "") { $error = 1; $email_error = 1; }
if ($num_checkemail > 0) { $error = 1; $email_error = 1; }
if ($password == "") { $error = 1; $password_error = 1; }
if ($password != $password_confirm) { $error = 1; $password_error = 1; }
if ($error != 1)
{
$password = md5($password);
$query_register = "INSERT INTO u_user(username,email,password,picture) VALUES ('$username','$email','$password')";
$run_register = mysql_query($query_register, $mycon);
$success = 1;
$_SESSION['auth'] = "yes";
$_SESSION['user_id'] = mysql_insert_id();
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Register</title>
<link rel="stylesheet" href="css/mycss.css" type="text/css">
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
// Run when document loaded
$(document).ready(function () {
//Cache Ajax Response Spans
var registerUsernameAjax = $('#registerUsernameAjax');
var registerEmailAjax = $('#registerEmailAjax');
var registerPasswordConfirmAjax = $('#registerPasswordConfirmAjax');
var registerCodeAjax = $('#registerCodeAjax');
//On key up in username input field
$('#username').keyup(function () {
//this points to the input field
var t = this;
//Only username change
if (t.value != t.lastValue) {
//Not on every key press
if (t.timer) clearTimeout(t.timer);
//Set spinner going while loading
registerUsernameAjax.html('<img src="images/spinner.gif" alt="">');
this.timer = setTimeout(function () {
$.ajax({
url: 'register_verify.php',
data: 'action=username&username=' + t.value,
dataType: 'json',
type: 'post',
success: function (response) {
var img = document.createElement("img");
img.src = ("images/" + response);
registerUsernameAjax.html(img);
}
});
}, 200);
t.lastValue = t.value;
}
});
//On key up in email input field
$('#email').keyup(function () {
var t = this;
if (t.value != t.lastValue) {
if (t.timer) clearTimeout(this.timer);
registerEmailAjax.html('<img src="images/spinner.gif" alt="">');
this.timer = setTimeout(function () {
$.ajax({
url: 'ajax/ajax_response.php',
data: 'action=email&email=' + t.value,
dataType: 'json',
type: 'post',
success: function (response) {
var img = document.createElement("img");
img.src = ("images/" + response);
registerEmailAjax.html(img);
}
});
}, 200);
t.lastValue = t.value;
}
});
//On key up in password confirm input field
$('#password_confirm').keyup(function () {
var t = this;
if (t.value != t.lastValue) {
if (this.timer) clearTimeout(t.timer);
registerPasswordConfirmAjax.html('<img src="images/spinner.gif" alt="">');
t.timer = setTimeout(function () {
var pword = document.getElementById('password').value;
var pconfirm = document.getElementById('password_confirm').value;
if (pword == pconfirm) {
var img = document.createElement("img");
img.src = ("images/ajax_yes.gif");
registerPasswordConfirmAjax.html(img);
}
else {
var img = document.createElement("img");
img.src = ("images/ajax_no.gif");
registerPasswordConfirmAjax.html(img);
}
}, 200);
t.lastValue = t.value;
}
});
});
</script>
</head>
<body>
<div id="content" style="text-align: center; background-color: #009966;">
<div id="registerText" class="textContentBox">
<div id="registerTitle" class="textLarge">
Register
</div>
<br>
<?php
if ($error == 1)
{
echo "<div class='textError'>";
echo " some data is wrong/missing";
echo " <br>".$photo_error_text;
echo "</div><br>";
}
if ($success != 1)
{
?>
<form id="register" name="register" action="register.php" enctype="multipart/form-data" method="post">
<div id="registerUsername">
<div id="registerUsernameLabel" class="textRegisterLabel">
username:
</div>
<div id="registerUsernameInput" class="textRegisterInput">
<?php
if ($username_error == 1) { $class = "formTextBoxError"; } else { $class = "formTextBox"; }
?>
<input id="username" name="username" type="text" value="<?php echo $username; ?>" class="<?php echo $class; ?>" size="32" maxlength="64">
<span id="registerUsernameAjax" style="float: right; position: relative; bottom: 20px; right: 25px;">
</span>
</div>
</div>
<br>
<br>
<div id="registerEmail">
<div id="registerEmailLabel" class="textRegisterLabel">
email:
</div>
<div id="registerEmailInput" class="textRegisterInput">
<?php
if ($email_error == 1) { $class = "formTextBoxError"; } else { $class = "formTextBox"; }
?>
<input id="email" name="email" type="text" value="<?php echo $email; ?>" class="<?php echo $class; ?>" size="32" maxlength="64">
<span id="registerEmailAjax" style="float: right; position: relative; bottom: 20px; right: 25px;">
</span>
</div>
</div>
<br>
<br>
<div id="registerPassword">
<div id="registerPasswordLabel" class="textRegisterLabel">
password:
</div>
<div id="registerPasswordInput" class="textRegisterInput">
<?php
if ($password_error == 1) { $class = "formTextBoxError"; } else { $class = "formTextBox"; }
?>
<input id="password" name="password" type="password" class="<?php echo $class; ?>" size="32" maxlength="32">
</div>
<br>
<div id="registerPasswordConfirmLabel" class="textRegisterLabel">
password confirm:
</div>
<div id="registerPasswordConfirmInput" class="textRegisterInput">
<?php
if ($password_confirm_error == 1) { $class = "formTextBoxError"; } else { $class = "formTextBox"; }
?>
<input id="password_confirm" name="password_confirm" type="password" class="<?php echo $class; ?>" size="32" maxlength="32">
<span id="registerPasswordConfirmAjax" style="float: right; position: relative; bottom: 20px; right: 25px;">
</span>
</div>
</div>
<br>
<br>
<div id="registerSubmit">
<input id="registerSubmitted" name="registerSubmitted" type="hidden" value="1">
<input id="registerSubmitButton" type="submit" value="Register" class="formSubmit">
</div>
<br>
</form>
<?php
}
else
{
?>
<div id="registerSuccess" class="textSuccess">
Your registration was successful
</div>
<br>
<div id="registerLogin" class="text">
You are now logged in. Click <a href="profile.php">here</a> toview your profile
</div>
<?php
}
?>
</div>
</div>
</body>
</html>
Lines 2-5, just start a session and setup the database connection.
Lines 7-41, is the usual verification and database queries that you get with registering. Nothing to do with ajax going on here.
Line 49, include the jquery script. Always remember this, often things don't work because I forget it or forget to close the script tag.
Lines 50-135, this is the Ajax/jQuery stuff and what we care about at the moment. Before you look at this you will need to look at
Lines 156-217 to get my naming convention for div & span id's. Stuff with somethingAjax is where ajax sends it response to the users entered data.
I'll now break down the ajax.
Line 52
$(document).ready(function () {
This waits for the document to load. The beauty of jQuery is that without it this is actually a quite hard thing to do and maintain cross-browser support. But by using jQuery all you need is this one line.
This creates an unnamed function that all your ajax code has to be inside. Note that it opens both a normal bracket ( and a curly bracket {, make sure you close both at the end as on line 134 with });
Lines 55-58 are not strictly needed, but it makes it easier. They assign elements to a variable.
var registerUsernameAjax = $('#registerUsernameAjax');
This assigns the element (in this case a span) with id 'registerUsernameAjax' to the variable of the same name (but can be anything you want).
Line 61 creates a function that runs whenever a key is released, i.e. when the user stops typing. This function is associated with the 'username' input text field. Note that the same syntax is used to reference to both spans and input fields. They are ways around this so you can have things with the same id, but I prefer it this way. Keeps things more obvious.
So if the user stops typing, lines 62-84 are run.
Line 63 just stops you from having to type out 'this' all the time, instead only 't'. A bit lazy, but useful.
Line 65 ensures the code only runs if the actual text in the field has changed since it last checked.
Line 67, 70 & 82 ensures it only runs at a minimum of once every 200 milliseconds, this stops it hogging everything.
Line 69 sets the html within the variable (which relates to the element) as an animated loading spinner image. The .html command
overwrites anything else inside the element. It doesn't append onto it.
Lines 71-81 is the actual ajax call. It is all contained in the special ajax function $.ajax({ ... }); Remember to put both types
of bracket around it, and in the right order.
The function holds various types of data.
The url: line points to where the ajax request is to be sent.
The data: line holds the data to send, and is written just like a GET request on any url, even if you want to send the data as a POST request. In this case it says what element is being looked at, here username, and what value it holds, t.value
The dataType: line says what type of data is going to be returned. There are different ways of doing this: xml, json, html, but I find json to be the simplest. Have a look into all and decide for yourself. The major problem with json is that you cannot send direct html as it parses the data and mangles html tags. But you can work around this.
The type: line can either be GET or POST.
The last bit is the what-to-do-if-it-works function. This function takes a variable that is the response from ajax call, you can call it anything, but I use 'response' as it makes it obvious.
You can put what you like in the success function, but in here I have made it create an img element (line 77), then update the
source of the image with the value of the response (line 78) then update the html in the registerUsernameAjax span with this image. The image source from the response is either a tick or a cross.
This functionality is pretty much copied for the rest of the input fields, with some changes for the password fields. Instead of calling for a response from an external file, it simply compares the password field with the password confirm field, and if they are the same output a tick else it outputs a cross.
register_verify.php
<?php
require_once("connection/mycon.php");
mysql_select_db($database_db, $mycon);
if ($_POST['action'] == "username")
{
$query_username = "SELECT id FROM u_user WHERE username='$_POST[username]'";
$run_username = mysql_query($query_username, $mycon);
if (mysql_num_rows($run_username) > 0)
{
echo json_encode("ajax_no.gif");
exit;
}
else
{
echo json_encode("ajax_yes.gif");
exit;
}
}
elseif ($_POST['action'] == "email")
{
$query_email = "SELECT id FROM u_user WHERE email='$_POST[email]'";
$run_email = mysql_query($query_email, $mycon);
if (mysql_num_rows($run_email) > 0)
{
echo json_encode("ajax_no.gif");
exit;
}
else
{
echo json_encode("ajax_yes.gif");
exit;
}
}
?>
Lines 5 & 21 determine what input field is being looked at, as said by the POST data sent to it via the ajax call.
For the username field, the value in the username field is searched for in the user database, and if it exists outputs a cross, else output a tick.
The important lines are 12-13 and 17-18.
echo json_encode("ajax_no.gif");
exit;
The first line encodes the text "ajax_no.gif" as json data type, then echos it. This is what the ajax call reads. The second line is there to ensure nothing else is read and that the file terminates once the return data is sent.
To see all this in action, go to www.emigrategame.com/iamboard/register.php
A username that is unavailable is 'Laz'
If you want any more clarification or help, just ask. Again, check out www.jquery.com for loads more stuff you can do with it.
Edit: edited to sort out formatting
As with most people I jump around which projects I work on and which I drop for a while.
Currently I'm back working on Sioux, a Hollywood Western RTS.