This tutorial is useful for obtaining data from a database using Ajax in PHP. Here you will find an original example. If you want to create an Ajax based project and build everything without reloading the page, then this example is perfect for you. After reading this complete tutorial, you will be able to see other various and complex data quickly.

Here we using 3 file for view data from MySql database using Ajax.

  1. database.php
  2. index.php
  3. ajax_data.php

Before to create files you need to create database and then create table following code will help to your database table

 CREATE TABLE `user_data` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone` varchar(100) NOT NULL,
  `city` varchar(100) NOT NULL


$servername = "localhost";
$username = "root";
$password = "";
$db = "tutorial";
// Create connection to db
$conn = mysqli_connect($servername, $username, $password, $db);


include 'database.php';
$sql = "SELECT * FROM user_data";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
            <td><?php= $row['name']; ?></td>
            <td><?php= $row['email']; ?></td>
            <td><?php= $row['phone']; ?></td>
            <td><?php= $row['city']; ?></td>
} else {
    echo "0 results";


<!DOCTYPE html>
<html lang="en">
        <title>View Ajax</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
        <script src=""></script>
        <script src=""></script>
        <script src=""></script>
        <div class="container">
            <h2>View data</h2>
            <table class="table table-bordered table-sm" >
                <tbody id="table">

                url: "ajax_data.php",
                type: "POST",
                cache: false,
                success: function(data) {


Download source code

Are you facing problems in understanding this article? download source code now