Web application with Ajax and Jquery

Web application with Ajax and Jquery

Sometimes when writing web applications you want to have a snappy experience, by not loading different pages with each page request, using Ajax (Asynchronous Javascript) you can load only parts of a page from the server for instance, this can save bandwidth and can render your web application more responsive.

Ajax (also AJAX) short for asynchronous JavaScript and XML) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications.

We are going to create simple PHP application that simply checks a MySQL database for a username and password, if you are unsure on how to run a PHP web application see the creating a PHP application tutorial. To start off we are to create a database with a table for users and we populate this with basic information for our user:

CREATE DATABASE ajaxtutorial;
USE ajaxtutorial;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL
);
INSERT INTO `users` (`id`, `username`, `password`) VALUES (1, 'vusani', 'pass');
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);

After creating our database we create 3 files namely "index.php, login.php, myscript.js" this is our main application structure we are to use, first we create a simple login form in the index.php file: note I'm using bootstrap 3 in this abstract

<div class="col-md-4 col-md-offset-4" id="mycontent">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">Sign In</h3>
                </div>
                <div class="panel-body">
                    <form accept-charset="UTF-8" method="POST" action="login.php" role="form" id="myform">
                    <fieldset>
                        <div class="form-group">
                            <input class="form-control" placeholder="Username" name="username" type="text" required="true">
                        </div>
                        <div class="form-group">
                            <input class="form-control" placeholder="Password" name="password" type="password" value="" required="true">
                        </div>
                        <input class="btn btn-lg btn-success btn-block" type="submit" value="Sign In">
                    </fieldset>
                    </form>
                </div>
            </div>
            </div>  

You may copy and paste this in the contents section of the index.php file, next thing we are to do is actually check if our user exists in the database so we are now editing the login.php file and returning JSON data to be processed by the web application

Initial Screen

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

What we do now is do a basic check on the database login.php:

$results = array();
$con = mysqli_connect("localhost", "root" , "","ajaxtutorial");
if (mysqli_connect_errno())
{
$results['valid'] = 1;
$results['msg'] = "Error connecting to database";
echo json_encode($results);
exit();
}
if(empty($_POST['username']) || empty($_POST['password']))
{
$results['valid'] = 1;
$results['msg'] = "The Username and Password are required";
echo json_encode($results);
exit();
}
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT id FROM users WHERE username = '".$user."' AND Password = '".$pass ."';";
$result =  mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) 
{
$results['valid'] = 0; //username and password are valid
$results['msg'] = "Login successful :-)";
echo json_encode($results);
exit();
}
$results['valid'] = 1;
$results['msg'] = "Username and/or Password incorrect";
echo json_encode($results);
mysqli_close($con);

I have inserted comments on the above snippets so you may better understand the code, and finally we are going to create the javascript that has all the processing for our results returned from the server, simply what this does is call login.php with a post request and posts the username and password for processing then upon results the content of the page is modified using javascript and id tags: 

jQuery(document).ready(function($) {
    $('#myform').submit(function() {
        $("#mysuccess, #myerror").addClass("hidden");
        var postdata = $('#myform').serialize(); //retrieve the username and password in json format
        $.ajax({
            type: 'POST',
            url: 'login.php',
            data: postdata, //pass the retrieved data json format
            dataType: 'json',
            success: function(json) {
                if(json.valid == 0) {
                    $("#mysuccess").html("<h1>"+json.msg+"</h1> <a class='btn btn-danger' href='index.php'>Logout</a>");
                    $("#mysuccess").toggleClass("hidden");
                    $("#mycontent").remove();
                } else {
                    $("#myerror").html(json.msg);
                    $("#myerror").toggleClass("hidden");
                }}});
        return false;
    });
});

And that's essentially what you need to post an Asynchronous request to a web server, try entering username and password and watch the results returned are processed on the page. To have the messages displayed upon returning results from the server add the error and success blocks in the index.php file:

<div class="alert alert-success hidden" role="alert" id="mysuccess"></div>
<div class="alert alert-danger hidden" role="alert" id="myerror"></div>

And you should have results as below :-)

Results of our work

Full project on Github:
https://github.com/vusani/ajax-tut