Retrieve Data Without Page Refresh Using Ajax in PHP

June 4, 2020
PHP
retrieve data using ajax

In this tutorial, we will create a Retrieve Data Without Page Refresh using Ajax. This code will retrieve the MySQLi table row when the user submits the form inputs. The code use jQuery ajax to immediately recover MySQLi table row server without a refreshing web page and display it as a readable data in the HTML table. This is a user-friendly kind of program that feels free to the user in your application.

We will be using jQuery, a JavaScript framework that designs to simplify HTML DOM tree traversal and manipulation. It can retrieve DOM and manipulate each property of an element based on different criteria such as id, class, etc.

Getting Started:

First, you have to download & install XAMPP or any local server that runs PHP scripts. Here’s the link for the XAMPP server https://www.apachefriends.org/index.html.

And this is the link for the jquery that I used in this tutorial https://jquery.com/.

Lastly, this is the link for the bootstrap that I used for the layout design https://getbootstrap.com/.

Creating Database

Open your database web server then create a database name in it db_retrieve, after that, click Import, then locate the database file inside the folder of the application then click ok.

retrieve data without refresh using ajax

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.

<?php
    $conn = mysqli_connect("localhost", "root", "", "db_retrieve") or die(mysqli_error());
    if(!$conn){
        die("Error: Failed to connect to database");
    }
?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as index.php.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
    </head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
        </div>
    </nav>
    <div class="col-md-3"></div>
    <div class="col-md-6 well">
        <h3 class="text-primary">PHP - Retrieve Data Without Page Refresh Using Ajax</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        <div class="col-md-4">
            <form method="POST">
                <div class="form-group">
                    <label>Firstname</label>
                    <input type="text" id="firstname" class="form-control"/>
                </div>
                <div class="form-group">
                    <label>Lastname</label>
                    <input type="text" id="lastname" class="form-control"/>
                </div>
                <div class="form-group">
                    <label>Age</label>
                    <input type="number" min="0" max="200" id="age" class="form-control"/>
                </div>
                <div class="form-group">
                    <label>Address</label>
                    <input type="text" id="address" class="form-control"/>
                </div>
                <center><button type="button" id="save" class="btn btn-primary"><span class="glyphicon glyphicon-save"></span> Save</button></center>
            </form>
        </div>
        <div class="col-md-8">
            <table class="table table-bordered">
                <thead class="alert-info">
                    <th>Firstname</th>
                    <th>Lastname</th>
                    <th>Age</th>
                    <th>Address</th>
                </thead>
                <tbody id="data" style="background-color:#fff;"></tbody>
            </table>
        </div>
    </div>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/script.js"></script>
</body>
</html>

Creating the Save Query

This code contains the save function of the application. This code will store the form data to MySQLi database. To make this just copy and write these block of codes below inside the text editor, then save it as save.php.

<?php
    require 'conn.php';
 
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $age = $_POST['age'];
    $address = $_POST['address'];
 
    mysqli_query($conn, "INSERT INTO `member` VALUES('', '$firstname', '$lastname', '$age', '$address')") or die(mysqli_error());
 
    echo "Save Data";
?>

Creating the Main Function

This code contains the main function of the application. This code will immediately display MySQLi table when the button is clicked. To make this just copy and write these block of codes below inside the text editor, then save it as shown below
data.php

<?php
    require 'conn.php';
 
    if(ISSET($_POST['res'])){
        $query = mysqli_query($conn, "SELECT * FROM `member` ORDER BY `lastname` ASC") or die(mysqli_error());
        while($fetch = mysqli_fetch_array($query)){
            echo 
            "<tr>
                <td>".$fetch['firstname']."</td>
                <td>".$fetch['lastname']."</td>
                <td>".$fetch['age']."</td>
                <td>".$fetch['address']."</td>
            </tr>";
        }
    }
?>

script.js
Note: To make the script works make sure you save this file inside the js directory.

$(document).ready(function(){
    displayData();
 
    $('#save').on('click', function(){
        var firstname = $('#firstname').val();
        var lastname = $('#lastname').val();
        var age = $('#age').val();
        var address = $('#address').val();
 
        if($('#firstname').val() == "" || $('#lastname').val() == "" || $('age').val() == "" || $('address').val()){
            alert("Please complete the required field");
        }else{
            $.ajax({
                type: 'POST',
                url: 'save.php',
                data: {
                    firstname: firstname,
                    lastname: lastname,
                    age: age,
                    address: address
                },
                success: function(data){
                    $('#firstname').val('');
                    $('#lastname').val('');
                    $('#age').val('');
                    $('#address').val('');
                    alert(data);
                    displayData();
                }
            })
        }
    });
 
    function displayData(){
        $.ajax({
            type: 'POST',
            url: 'data.php',
            data: {res: 1},
            success: function(data){
                $('#data').html(data)
            }
        });
    }
});

There you have it we successfully created Retrieve Data Without Page Refresh using Ajax. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

Facebook Comments
https://www.campcodes.com/

This is a free education portal. You can use every source code in your project without asking permission to the author. Share our website to everyone to make our community of programmers grow more.

Leave a Reply

Your email address will not be published.