PHP Crud Operation Using AJAX

Hello Coders, today we will learn about PHP Crud Operation Using AJAX which is very important for a PHP beginner who wants to learn about Ajax and also want to implement ajax based core PHP CRUD operation.

Ajax helps us to work without any page load and also from that we work in a fast way, loading speed is incredibly increased.

Here are the list of major PHP files which we create on whole PHP AJAX CRUD operation,

  1. Conn.php
  2. Index.php
  3. app.js
  4. add.php
  5. view.php
  6. edit.php
  7. update.php
  8. delete.php

So let’s start with the code and check the comments of the code for elaboration.

First, we create a database with the name whatever you want and make a connection file with that name.

Complete Source code of PHP Crud Operation Using AJAX

CRUD.sql

//table name
CREATE TABLE `userinfo` (
`id` int(5) NOT NULL,
`name` varchar(100) NOT NULL,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `userinfo`
  ADD PRIMARY KEY (`id`);

Here it is a connection file named,

Conn.php

<?php

global $con;
$con = mysqli_connect('localhost','root','','CRUD');
if(!$con)
{
 echo 'unable to connect with db';
 die();
}

after connectivity, we are going to add data to the database, before adding the code first we write code for design and giving ID to the all used fields, see below code

Index.php

<!DOCTYPE html>
<html>
  <head>
    <title>CRUD Ajax
    </title>
    <link type="text/css" href="css/bootstrap.min.css">
    <link type="text/css" href="css/bootstrap-theme.min.css">
  </head>
  <body>
    <div class="container-fluid" style="padding: 0px; margin: 0px;">
      <div class="jumbotron">
        <h1 class="text-center">CRUD Oprations Using AJAX
        </h1>
      </div>
    </div>
    <div class="container" style="padding-top: 25px;">
      <div class="row">
        <div class="col-md-12">
          <div class="pull-right">
            <button class="btn btn-success" id="show-add">Add New Record
            </button>
          </div>
          <div id="link-add" class="form-inline">
            <div class="form-group col-md-3">
              <input type="text" name="name" id="name" placeholder="Name" class="form-control" required />
            </div>
            <div class="form-group col-md-3">
              <input type="text" name="username" id="username" placeholder="Username" class="form-control" required/>
            </div>
            <div class="form-group col-md-3">
              <input type="text" id="password" name="password" placeholder="Password" class="form-control" required />
            </div>
            <div class="form-group col-md-3">
              <button type="button" class="btn btn-primary" id="add" name="add">Add Record
              </button>
              <button type="button" href="javascript:void(0);" class="btn btn-default" id="cancel" name="add" onclick="$('#link-add').slideUp(400);$('#show-add').show(600);">Cancel
              </button>
            </div>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12">
          <div id="records_content">
          </div>
          <br>
          <div class="col-md-offset-1 col-md-10" id="table_content">
          </div>
        </div>
      </div>
    </div>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js">
    </script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js">
    </script>
    <script src="app.js">
    </script>
  </body>
</html>

Now we write the query for inserting data on the database, before insertion we create a js or Ajax file for full CRUD operation. On this JS file, we using Jquery and Ajax, this is also the main file where all the operation is held. See below for the code

app.js

$(document).ready(function() {

    $.get("view.php", function(data) {
        $("#table_content").html(data);
    });

    $('#link-add').hide();

    $('#show-add').click(function() {
        $('#link-add').slideDown(500);
        $('#show-add').hide();
    });

    $('#add').click(function() {
        var name = $('#name').val();
        var username = $('#username').val();
        var password = $('#password').val();

        $.ajax({
            url: "add.php",
            type: "POST",
            data: {
                name: name,
                username: username,
                password: password
            },
            success: function(data, status, xhr) {
                $('#name').val('');
                $('#username').val('');
                $('#password').val('');
                $.get("view.php", function(html) {
                    $("#table_content").html(html);
                });
                $('#records_content').fadeOut(1100).html(data);
            },
            error: function() {
                $('#records_content').fadeIn(3000).html('<div class="text-center">error here</div>');
            },
            beforeSend: function() {
                $('#records_content').fadeOut(700).html('<div class="text-center">Loading...</div>');
            },
            complete: function() {
                $('#link-add').hide();
                $('#show-add').show(700);
            }
        });
    });
});

Now we create add query,

add.php

<?php
require_once ('conn.php');
global $con;

$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];

if (!empty($name) && !empty($username) && !empty($password))
{
    $query = $con->prepare("INSERT into userinfo (name, username, password) VALUES (?,?,?)");

    $query->bind_param('sss', $name, $username, $password);

    $result = $query->execute();

    if ($result)
    {
        echo '<div class="col-md-offset-4 col-md-5 text-center alert alert-success">1 Record Added!</div>';
    }
    else exit(mysqli_error($con));
}

For the viewing the file we are creating view file where data are getting from the database using PDO and MySql queries with Ajax.

view.php


<?php
require_once('conn.php');
global $con;

$query = $con->prepare("SELECT * FROM userinfo order by id DESC");
$query->execute();
mysqli_stmt_bind_result($query, $id, $name, $username, $password);
?>
<table class="table table-bordered">
<tr class="info">
<th>ID</th>
<th>Name</th>
<th>Username</th>
<th>Password</th>
<th>Action</th>
</tr>
<?php

while(mysqli_stmt_fetch($query))
{
echo '
<tr>
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>'.$username.'</td>
<td>'.$password.'</td>
<td><button id="'.$id.'" class="edit btn btn-info">Edit</button> <button class="del btn btn-danger" id="'.$id.'">Delete</button></td>
</tr>';
}
echo '</table>';

?>
<script type="text/javascript">
  $('.del').click(function() {
    var id = $(this).attr('id');
    $.ajax({
      url : "delete.php",
      type: "POST",
      data : {
        id: id }
      ,
      success: function(data)
      {
        $('#records_content').fadeOut(1100).html(data);
        $.get("view.php", function(data)
              {
          $("#table_content").html(data);
        });
      }
    });
  });
  // delete close
  $('.edit').click(function() {
    var id = $(this).attr('id');
    $('#show-add').hide();
    $.ajax({
      url : 'edit.php',
      type: 'POST',
      data : {
        id: id }
      ,
      success: function(data)
      {
        $("#link-add").html(data);
        $('#link-add').show();
      }
    });
  });
  // edit close
</script>

Now we create the Edit file where edit design is available with dynamic data for updating.

 edit.php


<?php

require_once('conn.php');
global $con;
$id = $_POST['id'];

if(empty($id))
{
?><div class="text-center">no records found under this selection <a href="#" onclick="$('#link-add').hide();$('#show-add').show(700);">Hide this</a></div>
<?php
die();
}

$query = "SELECT * FROM userinfo where id='$id'";
if (!$result = mysqli_query($con, $query)) {
exit(mysqli_error($con));
}
while($row = mysqli_fetch_assoc($result))
{
?>
<div class="form-inline" id="edit-data">
  <div class="form-group col-md-3">
    <input type="text" name="name" id="name" value="<?php echo $row['name']; ?>" placeholder="Name" class="form-control" required />
  </div>
  <div class="form-group col-md-3">
    <input type="text" name="username" id="username" placeholder="Username" class="form-control" value="<?php echo $row['username']; ?>" required/>
  </div>
  <div class="form-group col-md-3">
    <input type="text" id="password" name="password" placeholder="Password" class="form-control" value="<?php echo $row['password']; ?>" required />
  </div>
  <div class="form-group col-md-3">
    <button type="button" class="btn btn-primary update" id="<?php echo $row['id']; ?>" name="update">Update Record
    </button>
    <button type="button" href="javascript:void(0);" class="btn btn-default" id="cancel" name="add" onclick="$('#link-add').slideUp(400);$('#show-add').show(700);">Cancel
    </button>
  </div>
<?php
}
?>

<script type="text/javascript">
$('.update').click(function() {
    var id = $(this).attr('id');
    var name = $('#name').val();
    var username = $('#username').val();
    var password = $('#password').val();

    $.ajax({
        url: "update.php",
        type: "POST",
        data: {
            id: id,
            name: name,
            username: username,
            password: password
        },
        success: function(data, status, xhr) {
            $('#name').val('');
            $('#username').val('');
            $('#password').val('');
            $('#records_content').fadeOut(1100).html(data);
            $.get("view.php", function(html) {
                $("#table_content").html(html);
            });
            $('#records_content').fadeOut(1100).html(data);
        },
        complete: function() {
            $('#link-add').hide();
            $('#show-add').show(700);
        }
    });
}); // update close
</script>

Here is now for updating the fetched data we create a query for updating. See the code below

update.php

<?php
require_once ('conn.php');
global $con;

$id = $_POST['id'];
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];

if (!empty($name) && !empty($username) && !empty($password) && !empty($id))
{
    $query = "UPDATE userinfo SET name='$name', username='$username', password='$password' WHERE id='$id'";
    if (!$result = mysqli_query($con, $query))
    {
        exit(mysqli_error($con));
    }
    echo '<div class="col-md-offset-4 col-md-5 text-center alert alert-success">1 Record updated!</div>';
}
else
{
    echo '<div class="col-md-offset-4 col-md-5 text-center alert alert-danger">error while updating record</div>';
}

Now, this is the last which is delete operation.

delete.php

<?php
require_once ('conn.php');
global $con;

$id = $_POST['id'];

if (empty($id))
{
    die();
}
$query = $con->prepare("DELETE FROM userinfo where id=?");

$query->bind_param('i', $id);

$result = $query->execute();

if ($result)
{
    echo '<div class="col-md-offset-4 col-md-5 text-center alert alert-success">1 Record Deleted!</div>';
}
else
{
    exit(mysqli_error($con));
}

[sociallocker]Download Complete File: Click Here[/sociallocker]

Note: Please link your bootstrap files. (CSS and JS)

To know more about PHP, go for PHP official site https://php.net

Also Read:

Happy Coding..!

Was this article helpful?
YesNo
My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH, my native place in Odisha. I am a Web Programmer by profession and working on more than 50 projects to date. My passion is working on the web-based project using PHP and relate to all CMS and frameworks which is based on PHP.
Posts created 163

11 thoughts on “PHP Crud Operation Using AJAX

    1. Sorry for your inconvenience. Because of server migration that file had missed from server.
      Please send me a mail at [email protected] and I will provide the complete file on same.
      Thanks for your time.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
mariobet - supertotobet - escort -

takip7.com

We are now accepting Guest Posting and creation of Backlinks
This is default text for notification bar