开发者

PHP, AJAX for Signup Form

I am trying to set up my first PHP site and I really want to do it the right way. I am working on the form located: http://www.bwgblog.com/signup.

I have set up the following form:

            <p><form action="/signup/register.php" method="post">

                    <label for="first_name">First Name</label>
                    <input type="text" name="first_name" />

                    <label for="last_name">Last Name</label>
                    <input type="text" name="last_name" />

                    <label for="company">Company</label>
                    <input type="text" name="company" />

                    <label for="job_title">Job Title</label>
                    <input type="text" name="job_title" />

                    <label for="phone">Phone</label>
                    <input type="text" name="phone" />

                    <label for="email">Email</label>
                    <input type="text" name="email" />

                    <label for="username">Choose a Username</label>
                    <input type="text" name="username" />

                    <label for="password">Choose a Password</label>
                    <input type="text" name="password" />

                    <label for="confirm_password">Confirm Your Password</label>
                    <input type="text" name="confirm_password" />

                    <input type="submit" value="Get Started" />

                    </form>

And here is my PHP page, register.php:

    <?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$con = mysql_connect("localhost","*******","******"); //Replace with your actual MySQL DB Username and Password
if (!$con) 
{ 
die('Could not connect: ' . mysql_error()); 
} 
mysql_select_db("bwgblog", $con); //Replace with your MySQL DB Name
$first_name=mysql_real_escape_string($_POST['first_name']); 
$last_name=mysql_real_escape_string($_POST['last_name']); 
$company=mysql_real_escape_string($_POST['company']);
$job_title=mysql_real_escape_string($_POST['job_title']); 
$phone=mysql_real_escape_string($_POST['phone']);
$email=mysql_real_escape_string($_POST['email']); 
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']); 
$confirm_password=mysql_real_escape_string($_POST['confirm_password']);  

$sql="INSERT INTO members (first_name,last_name,company,job_title,phone,email,username,password,confirm_password) VALUES ('$first_name','$last_name','$company','$job_title','$phone','$email','$username','$password','$confirm_password')"; 

if (!mysql_q开发者_StackOverflow中文版uery($sql,$con)) {
 die('Error: ' . mysql_error()); 
} 

echo "The form data was successfully added to your database."; 
mysql_close($con);
?>

I am trying to figure out how to add in AJAX such that it gives me two things. 1) The ability for it to check in realtime the username field as that field should be unique, and 2) the ability to have the confirm password field render a green checkmark if it == password field.

I have been looking all day for how to do this and can't get a clear look at it. Here is how the files are laid out:

signup (folder) -> index.php -> register.html.php -> register.php


1) AJAX doesn't require the backend to be anything special - so the simplest solution there may be to have a 'usercheck.php' file that queries the DB for the username passed, then returns some form of true/false. You'll probably want to reply using JSON (this is easy if you have PHP 5 - see json_encode).

Regarding the AJAX frontend you'll find it easiest if you use an existing framework (I've used Mochikit and prototype, both seem fine) of which there are several. This should allow you to load the server's response easily.

If you have the AJAX use GET rather than POST (this is simpler) then you can test the response by just viewing the page with the appropriate query string. In any case using Firebug will allow you to view the calls in realtime.

2) There is no need to have the password check AJAX - that can be done simply using plain JavaScript: simply compare the .value properties of the two inputs.


Agreed with PeterJCLaw on all accounts except the choice of javascript framework. Here is how you could do it with jQuery:

// give the form an ID to use a better selector: ie: $('#myform')
// intercept form submit

$('form').submit(function(){

    // check if passwords match; you might want to do more thorough validation
    if($('input[name=password]').val()==$('input[name=confirm_password]').val()){

         // make ajax post request and store the response in "response" variable
         $.post('/signup/register.php', $(this).serialize(), function(response){

             // process response here (assume JSON object has boolean property "ok"
             if(response.ok==true){
                 // sweet, it worked!
                 alert('OK!');
             }else{
                 // handle error
                 alert('Ooops');
             }
         }, 'json');

         // stop the form from being submitted
         return false;
    }else{
        // for the sake of simplicity
        alert('Passwords don't match!);
    }
});


Look at Jquery's validate extension.

It will simplify all of this. Checking remote values is simple too.

A relatively recent post on this with example code.

You can upload Jquery to your server, or google code hosts them. Using the google version greatly increases the chance that your customers will have already downloaded it also and can use their cached copy.


$fields = array('first_name','last_name','company','job_title','phone','email','username','password','confirm_password');

$dbfields = array(); $dbdata = array(); $dbfieldq = array(); $types = ''; //Setting Variable    

foreach ($fields as $field){ //For Each Field
if (!isset($_POST[$field]){ header('Location: signup.php'); die('Please Fill in all fields, they are required'); } //Missing Field Error -- Doublecheck on serverside
array_push($dbdata, strip_tags($_POST[$field])); //Add Data - MySQLi Prepared Statements don't need to be escaped
array_push($dbfields,$field); //Add a field
array_push($dbfieldq,'?'); //Add a ?
$types += 's'; //Add a field type (string for all of these)
}

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db'); //Connect

if ($mysqli->connect_error) { //If there is a connect Error
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}
$names = explode($dbfields); //Explode the Field Names
$questions = explode($dbfieldq); //Explode the ?
$stmt = $mysqli->prepare("INSERT INTO DBName ($names) VALUES ($questions)"); 
$params = $this->paramValues;
array_unshift($dbdata, implode($this->paramTypes);
call_user_func_array( array( $stmt, 'bind_param' ), $params);
$stmt->bind_param($types, $code, $language, $official, $percent);
$stmt->execute();
$mysqli->close();

A better way to do the php... Use prepared statements and loops to prepare the variables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜