Connecting to server and database using Ajax

In this tutorial, we are going to see how to connect to a server and read and write to a database using Ajax. We will use the same syntax of writing Ajax using Jquery as introduced in the previous tutorial.

We will build an Ajax script to check whether a username has been registered or not.

Step 1 – User Input

The user fills in an input field providing the username.

Step 2 – Check empty field

On clicking the Submit button, the jquery function is executed which checks whether the user has filled in the username or left the field empty.

Step 3 – Run Ajax Function

If the username has been filled, then the loader image is shown and ajax function is run to connect to the file ajax.php.

Step 4 – Run Ajax.php

In ajax.php, we connect to the server and check if the username is already registered in our database. If the user is not registered, then the message Username is available is shown otherwise the message This username is already registered is shown.

Step 5 – Return Output To Index Page

This output is then returned to the index page. If output is returned, then the process has been successful and user is shown the output otherwise the error message is shown.

Database

Table Structure

Index.php

<html>
<head>

<!-- Including the jquery library file-->
<script src="jquery.min.js"></script>

<script>
//Building the function to run Ajax script
$(document).ready(function(){
    $("button").click(function(){

        //Getting value of username filled in by the user
        var uname = $('#name').val();

        if(uname=="")
            alert("Please enter username");
        else{


            $.ajax({
                type: 'GET',
                url: 'ajax.php',
                data: {username:uname},
                beforeSend:function(){
                    $('#loader').show();
                },
                success:function(data){
                    $('#loader').hide();
                    //$("#div1").load("ajax.php");
                    $("#div1").html(data);
                    console.log(data);
                },
                error:function(){
                    $('#loader').hide();
                    $("#div1").html('<p style="color:red;">Some error occurred. Please try again.</p>');
                }
              });

        }

    });
});
</script>
</head>
<body>

<input type="text" id="name" name="name" placeholder="Enter username" /><br><br>

<div id="loader" style="display:none;"><img src="ajax-loader.gif" /></div>
<div id="div1"></div>

<button>Submit</button>
</body>
</html>

Ajax.php

<?php

    include 'config.php';
    if(isset($_GET['username'])){
        $name =  $_GET['username'];
        $query = mysql_query("SELECT * FROM `users` WHERE `username`='$name'");
        if(mysql_num_rows($query)){
            echo '<p style="color:red;">This username is already registered.</p>';
        }
        else
            echo '<p style="color:green;">This username is available.</p>';
    }
?>

Config.php

<?php
    $host = 'localhost';
    $user = 'root';
    $pwd = '';
    $db = 'ajaxbasics';
    $conn = mysql_connect($host,$user,$pwd); 
    $condb = mysql_select_db($db);
    if(!$conn ||  !$condb)
    {
        die('Connection error');
    }
?>

Loader.gif

Loader image

This image is shown momentarily before the ajax file is executed. This is shown to indicate that the file is running in the background. So in the beforeSend function, we show the image and hide it in the success and error functions.

Index page

Index Page

Intital Database

Database

Message shown when user is already registered

User already registered

Message shown when new user is added

New user registered

Updated database after adding new user

Updated database

Please feel free to download the source code and database for reference.

View Demo Download source

This content has been helpful to you?

Thanks for contributing!

Yes No