PHP ajax signup form – using MySQL and Jquery

Today we will create a simple PHP ajax signup form using MySQL and Jquery.

Let’s get started and create a table that will hold the users information for our simple PHP ajax signup form.

The fields we need are the following:

  • id – this is our private key and it will be auto increasing its value.
  • username – the desired username.
  • email – the user’s email.
  • password – the desired password(stored as a hash).

Here is how to create it:

[code language=”sql”]
CREATE TABLE IF NOT EXISTS `Users` (
`id` int(11) NOT NULL,
  `username` varchar(20) NOT NULL,
  `password` varchar(250) NOT NULL,
  `email` varchar(60) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

ALTER TABLE `Users`
 ADD PRIMARY KEY (`id`);
[/code]

Now since we have our table we need to insert some users into it. Because we are going to use ajax in our signup form we don’t need a php file.
A simple HTML will do the job, so here the magic starts!

signUp.html

[code language=”html”]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="css/style.css">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="js/signup.js" type="text/javascript"></script>
</head>
<body>
<div class="login-card">
<h1>Log-in</h1><br>
<form>
<input type="text" id="username" name="user" placeholder="Username">
<input type="text" id="email" name="email" placeholder="email">
<input type="password" id="password" name="pass" placeholder="Password">
<input type="button" id="signUp" name="signup" class="login login-submit" value="Sign up">
</form>
</div>
</body>
</html>
[/code]

The above signup form needs to be designed, so create a css folder and style.css into it. Here is the content:

style.css

[code language=”css”]
@import url(http://fonts.googleapis.com/css?family=Roboto:400,100);

body {
    background: url(https://dl.dropboxusercontent.com/u/23299152/Wallpapers/wallpaper-22705.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    font-family: ‘Roboto’, sans-serif;
}

.login-card {
    padding: 40px;
    width: 274px;
    background-color: #F7F7F7;
    margin: 0 auto 10px;
    border-radius: 2px;
    box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    overflow: hidden;
}

.login-card h1 {
    font-weight: 100;
    text-align: center;
    font-size: 2.3em;
}

.login-card input[type=submit] {
    width: 100%;
    display: block;
    margin-bottom: 10px;
    position: relative;
}

.login-card input[type=text], input[type=password] {
    height: 44px;
    font-size: 16px;
    width: 100%;
    margin-bottom: 10px;
    -webkit-appearance: none;
    background: #fff;
    border: 1px solid #d9d9d9;
    border-top: 1px solid #c0c0c0;
    /* border-radius: 2px; */
    padding: 0 8px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
}

.login-card input[type=text]:hover, input[type=password]:hover {
    border: 1px solid #b9b9b9;
    border-top: 1px solid #a0a0a0;
    -moz-box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
    -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
    box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
}

.login {
    text-align: center;
    font-size: 14px;
    font-family: ‘Arial’, sans-serif;
    font-weight: 700;
    height: 36px;
    padding: 0 8px;
    /* border-radius: 3px; */
    /* -webkit-user-select: none;
      user-select: none; */
}

.login-submit {
    /* border: 1px solid #3079ed; */
    border: 0px;
    color: #fff;
    text-shadow: 0 1px rgba(0,0,0,0.1);
    background-color: #4d90fe;
    /* background-image: -webkit-gradient(linear, 0 0, 0 100%,   from(#4d90fe), to(#4787ed)); */
}

.login-submit:hover {
    /* border: 1px solid #2f5bb7; */
    border: 0px;
    text-shadow: 0 1px rgba(0,0,0,0.3);
    background-color: #357ae8;
    /* background-image: -webkit-gradient(linear, 0 0, 0 100%,   from(#4d90fe), to(#357ae8)); */
}

.login-card a {
    text-decoration: none;
    color: #666;
    font-weight: 400;
    text-align: center;
    display: inline-block;
    opacity: 0.6;
    transition: opacity ease 0.5s;
}

.login-card a:hover {
    opacity: 1;
}

.login-help {
    width: 100%;
    text-align: center;
    font-size: 12px;
}
[/code]

Congratulations! You already have your signup form and you are a step ahead of registering your user using ajax and PHP!

Next create a javascript that will handle the ajax request.

So create a js folder and place a file named signup.js into it.

signup.js

[code language=”javascript”]
$(document).ready(function () {
    /* Catch the sign up button click event */
    $("#signUp").click(function () {
        /* Send the request to teh server */
        $.ajax({
            type: ‘POST’, // The request type POST or GET
            url: "app/controller.php", // The URL to the controller
            dataType: ‘html’, // The data type json, html, img etc…
            async: true, // async or sync
            /* The main request body */
            data: {
                action: "signUp", // The action that we are catching at controller.php
                username: $(‘#username’).val(), // Get the username user input
                email:    $("#email").val(), // Get the email user input
                password: $(‘#password’).val() // Get the password user input
            },
            success: function (data) {
                /* We are getting here, if everything is ok */
                alert("User registered!");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                /* If something goes wrong we’re comming here */
                alert(errorThrown);
            }
        });
    });
});
[/code]

Ok, Sparky!

Since you’re reading this it means that everything woked out for you. Ok then – create a new folder named app and place 3 php files in it:

  • config.php – it will hold the database connection variables
  • dbAssistant.php – we will create the functions holding our queries in it
  • controller.php – it will handle our ajax request and execute specific functions of dbAssistant.php

config.php

[code language=”php”]
<?php

$host = "localhost"; //your hostname here
$dbName = "dbName"; //your database name here
$dbUsername = "dbUsername"; //your database username here
$dbPassword = "dbPassword"; // your database password here

?>
[/code]

constroller.php

[code language=”php”]
<?php

/* include the configuration and the functions files */
include ‘./config.php’;
include ‘./dbAssistant.php’;

/* Check if the session exists, if not start it */
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

/* Catch the action sent from teh ajax request */
$action = filter_input(INPUT_POST, ‘action’);

/* Check teh ajax action */
if($action == "signUp"){
    /* Encrypt the password */
    $encryptedPassword = password_hash(filter_input(INPUT_POST, ‘password’), PASSWORD_DEFAULT);
    /* Execute the function that inserts the user into teh database */
    signUp(filter_input(INPUT_POST, ‘username’), filter_input(INPUT_POST, ’email’), $encryptedPassword, $host, $dbUsername, $dbPassword, $dbName);
}

?>
[/code]

dbAssistant.php

[code language=”php”]
<?php

/* Check if the session is started, if not then start it */
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

/* Sign up function – executed from controller.php */
function signUp($username, $email, $password, $host, $dbUsername, $dbPassword, $dbName) {

    /* Create connection */
    $mysqli = new mysqli($host, $dbUsername, $dbPassword, $dbName);

    /* The query that will be executed */
    $insertBannerAdQ = "INSERT INTO Users1(username, email, password) VALUES(?, ?, ?)";

    /* Execute teh query */
    if ($stmt = $mysqli->prepare($insertBannerAdQ)) {

        $stmt->bind_param(‘sss’, $username, $email, $password);

        $stmt->execute();
        
        /* close statement */
        $stmt->close();
    }

    $mysqli->close();
http_response_code(200);
}

?>
[/code]

That’s it!
If you follow this tutorial step by step, you have a working ajax sign up form.

Mind that you have to check if the username, password and email fields are filled before you send your request to the server.

[button-green url=”https://github.com/gelasoftDevs/simpleRegistrationForm” target=”blank” position=”center”]Find it on GitHub[/button-green]

Tags: , , ,

Search