PHP Jquery Ajax CRUD Example Tutorial From Scratch

PHP Jquery Ajax CRUD Example Tutorial From Scratch

Today, We want to share with you PHP Jquery Ajax CRUD Example Tutorial From Scratch.In this post we will show you Jquery Ajax CRUD Operations in PHP, hear for PHP MySQL CRUD Operations using jQuery and Bootstrap we will give you demo and example for implement.In this post, we will learn about Simple PHP Jquery Ajax CRUD(insert update delete) tutorial example with an example.

PHP Jquery Ajax CRUD Example Tutorial From Scratch

There are the Following The simple About PHP Jquery Ajax CRUD Example Tutorial From Scratch Full Information With Example and source code.

As I will cover this Post with live Working example to develop CRUD Operation using PHP/MySQLi and AJAX/jQuery, so the some major files and Directory structures for this example is following below.

  • index.php
  • fetchMemberData.php
  • create.php
  • edit.php
  • update.php
  • delete.php
  • js/member-ajax.js

Step 1: Make Mysql Database and Table

Items Table Query:

CREATE TABLE IF NOT EXISTS `members` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `membername` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `member_info` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=63 ;

Step 1.1 create database configuration

api/config_database.php

<?php
//CRUD Operation using PHP/MySQLi and AJAX/jQuery
    $hostName = "localhost";
    $username = "root";
    $password = "root";
    $dbname = "atmiya25";
    $mysqli = new mysqli($hostName, $username, $password, $dbname);
?>

Step 2: Create HTML interface Index Page

index.php

This is where I will make a simple HTML form and PHP server side source code for our web application. To make the forms simply all souce code copy and write it into your any text editor Like Notepad++, then save file it as index.php.

<!DOCTYPE html>
<html>
<head>
    <title>PHP Jquery Ajax CRUD Example - pakainfo.com</title>
    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
 
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/twbs-pagination/1.3.1/jquery.twbsPagination.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
    <link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet">
    <script type="text/javascript">
        var url = "http://localhost:8000/";
    </script>
    <script src="/js/member-ajax.js"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-lg-12 margin-tb">                    
                <div class="pull-left">
                    <h2>PHP Jquery Ajax CRUD Example</h2>
					<b>PHP Jquery Ajax CRUD Example Tutorial From Scratch</b>
                </div>
                <div class="pull-right">
                <button type="button" class="btn btn-success" data-toggle="modal" data-target="#create-member">
                      Create Member
                </button>
                </div>
            </div>
        </div>
        <table class="table table-bordered">
            <thead>
                <tr>
                <th>Member Name</th>
                <th>Member Information</th>
                <th width="200px">Action</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        <ul id="pagination" class="pakainfo pagination-sm"></ul>
        <!-- amke Member Modal -->
        <div class="modal fade" id="create-member" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title" id="myModalLabel">Create Member</h4>
              </div>
              <div class="modal-body">
                      <form data-toggle="validator" action="api/create.php" method="POST">
                          <div class="form-group">
                            <label class="control-label" for="membername">Member Name:</label>
                            <input type="text" name="membername" class="form-control" data-error="Please enter membername." required />
                            <div class="help-block with-errors"></div>
                        </div>
                        <div class="form-group">
                            <label class="control-label" for="membername">Member Information:</label>
                            <textarea name="member_info" class="form-control" data-error="Please enter member_info." required></textarea>
                            <div class="help-block with-errors"></div>
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn crud-submit btn-success">Submit</button>
                        </div>
                      </form>
              </div>
            </div>
          </div>
        </div>
        <!-- Edit Member Modal -->
        <div class="modal fade" id="edit-member" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title" id="myModalLabel">Edit Member</h4>
              </div>
              <div class="modal-body">
                      <form data-toggle="validator" action="api/update.php" method="put">
                          <input type="hidden" name="id" class="edit-id">
                          <div class="form-group">
                            <label class="control-label" for="membername">Member Name:</label>
                            <input type="text" name="membername" class="form-control" data-error="Please enter membername." required />
                            <div class="help-block with-errors"></div>
                        </div>
                        <div class="form-group">
                            <label class="control-label" for="membername">Member Information:</label>
                            <textarea name="member_info" class="form-control" data-error="Please enter member_info." required></textarea>
                            <div class="help-block with-errors"></div>
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-success crud-submit-edit">Submit</button>
                        </div>
                      </form>
              </div>
            </div>
          </div>
        </div>
    </div>
</body>
</html>

Step 3: Make PHP jQuery CRUD JS File

js/member-ajax.js

$( document ).ready(function() {
var page = 1;
var current_page = 1;
var total_page = 0;
var is_ajax_fire = 0;
manageData();
/* manage data list */
function manageData() {
    $.ajax({
        dataType: 'json',
        url: url+'api/fetchMemberData.php',
        data: {page:page}
    }).done(function(data){
        total_page = Math.ceil(data.total/10);
        current_page = page;
        $('#pagination').twbsPagination({
            totalPages: total_page,
            visiblePages: current_page,
            onPageClick: function (event, pageL) {
                page = pageL;
                if(is_ajax_fire != 0){
                  getPageData();
                }
            }
        });
        manageRow(data.data);
        is_ajax_fire = 1;
    });
}
/* Get Page Data*/
function getPageData() {
    $.ajax({
        dataType: 'json',
        url: url+'api/fetchMemberData.php',
        data: {page:page}
    }).done(function(data){
        manageRow(data.data);
    });
}
/* Add new Member table row */
function manageRow(data) {
    var    rows = '';
    $.each( data, function( key, value ) {
          rows = rows + '<tr>';
          rows = rows + '<td>'+value.membername+'</td>';
          rows = rows + '<td>'+value.member_info+'</td>';
          rows = rows + '<td data-id="'+value.id+'">';
        rows = rows + '<button data-toggle="modal" data-target="#edit-member" class="btn btn-primary edit-member">Edit</button> ';
        rows = rows + '<button class="btn btn-danger remove-member">Delete</button>';
        rows = rows + '</td>';
          rows = rows + '</tr>';
    });
    $("tbody").html(rows);
}
/* Create new Member */
$(".crud-submit").click(function(e){
    e.preventDefault();
    var form_action = $("#create-member").find("form").attr("action");
    var membername = $("#create-member").find("input[name='membername']").val();
 
    var member_info = $("#create-member").find("textarea[name='member_info']").val();
    if(membername != '' && member_info != ''){
        $.ajax({
            dataType: 'json',
            type:'POST',
            url: url + form_action,
            data:{membername:membername, member_info:member_info}
        }).done(function(data){
            $("#create-member").find("input[name='membername']").val('');
            $("#create-member").find("textarea[name='member_info']").val('');
            getPageData();
            $(".modal").modal('hide');
            toastr.success('Member Created Successfully.', 'Success Alert', {timeOut: 5000});
        });
    }else{
        alert('You are missing membername or member_info.')
    }
});
/* Remove Member */
$("body").on("click",".remove-member",function(){
    var id = $(this).parent("td").data('id');
    var c_obj = $(this).parents("tr");
    $.ajax({
        dataType: 'json',
        type:'POST',
        url: url + 'api/delete.php',
        data:{id:id}
    }).done(function(data){
        c_obj.remove();
        toastr.success('Member Deleted Successfully.', 'Success Alert', {timeOut: 5000});
        getPageData();
    });
});
/* Edit Member */
$("body").on("click",".edit-member",function(){
    var id = $(this).parent("td").data('id');
    var membername = $(this).parent("td").prev("td").prev("td").text();
    var member_info = $(this).parent("td").prev("td").text();
 
    $("#edit-member").find("input[name='membername']").val(membername);
    $("#edit-member").find("textarea[name='member_info']").val(member_info);
    $("#edit-member").find(".edit-id").val(id);
});
/* Updated new Member */
$(".crud-submit-edit").click(function(e){
    e.preventDefault();
    var form_action = $("#edit-member").find("form").attr("action");
    var membername = $("#edit-member").find("input[name='membername']").val();
    var member_info = $("#edit-member").find("textarea[name='member_info']").val();
    var id = $("#edit-member").find(".edit-id").val();
    if(membername != '' && member_info != ''){
        $.ajax({
            dataType: 'json',
            type:'POST',
            url: url + form_action,
            data:{membername:membername, member_info:member_info,id:id}
        }).done(function(data){
            getPageData();
            $(".modal").modal('hide');
            toastr.success('Member Updated Successfully.', 'Success Alert', {timeOut: 5000});
        });
    }else{
        alert('You are some missing membername or member_info.')
    }
});
});

Step 4: Make a Server Side AJAX File Call and Crud PHP

api/fetchMemberData.php

<?php
require 'config_database.php';
$num_rec_per_page = 5;
if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$sqlTotal = "SELECT * FROM members";
$sql = "SELECT * FROM members Order By id desc LIMIT $start_from, $num_rec_per_page"; 
$db_query_results = $mysqli->query($sql);
  while($row = $db_query_results->fetch_assoc()){
     $json[] = $row;
  }
  $data['data'] = $json;
$db_query_results =  mysqli_query($mysqli,$sqlTotal);
$data['total'] = mysqli_num_rows($db_query_results);
echo json_encode($data);
?>

Jquery Ajax CRUD Operations in PHP Create Member

api/create.php

<?php
require 'config_database.php';
  $post = $_POST;
  $sql = "INSERT INTO members (membername,member_info) 
    VALUES ('".$post['membername']."','".$post['member_info']."')";
  $db_query_results = $mysqli->query($sql);
  $sql = "SELECT * FROM members Order by id desc LIMIT 1"; 
  $db_query_results = $mysqli->query($sql);
  $data = $db_query_results->fetch_assoc();
echo json_encode($data);
?>

Jquery Ajax CRUD Operations in PHP Update

api/update.php

<?php
  require 'config_database.php';
  $id  = $_POST["id"];
  $post = $_POST;
  $sql = "UPDATE members SET membername = '".$post['membername']."'
    ,member_info = '".$post['member_info']."' 
    WHERE id = '".$id."'";
  $db_query_results = $mysqli->query($sql);
  $sql = "SELECT * FROM members WHERE id = '".$id."'"; 
  $db_query_results = $mysqli->query($sql);
  $data = $db_query_results->fetch_assoc();
  echo json_encode($data);
?>

crud php mysql ajax bootstrap – delete

api/delete.php

<?php
 require 'config_database.php';
 $id  = $_POST["id"];
 $sql = "DELETE FROM members WHERE id = '".$id."'";
 $db_query_results = $mysqli->query($sql);
 echo json_encode([$id]);
?>

run this example on terminal run commands

php -S localhost:8000

run Web Project and Browser URL

http://localhost:8000

Angular 6 CRUD Operations Application Tutorials

Read :

  CKEditor Upload files Custom File Manager using PHP

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about PHP Jquery Ajax CRUD Example Tutorial From Scratch.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Reply

avatar
  Subscribe  
Notify of