JQuery Ajax CRUD Operations in PHP MySQL Example

By Hardik Savani May 14, 2024 Category : PHP Javascript Bootstrap jQuery MySql Ajax

Hi Guys,

In this tutorial, i would like to show you how to create add edit delete and pagination operations using jquery ajax in php. You have to just follow 4 step to create php crud operation using ajax/jquery with bootstrap. I also added jquery validation using validatorjs plugin.

In this post, i crud with i also created pagination, notification and also validation in crud operation. When you will add new item then show you "item created successfully" notification. So just follow listed few step and you will get crud app like as below screen shot:

you can implement crud application from scratch, so no worry if you can implement through bellow simple step. After create successful example, you will find layout as bellow:

Preview:

Step 1: Create Database and Table Configuration

first of all, we should create database and items table. so let's create database i did create "h_blog" database and "items" table inside that database. so you can create database as you want but you have to create "items" table if you are doing from scratch. so create "items" table using following mysql query:

Items Table Query:

CREATE TABLE IF NOT EXISTS `items` (

`id` int(10) unsigned NOT NULL AUTO_INCREMENT,

`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

`description` text COLLATE utf8_unicode_ci NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=63 ;

Ok, let's proceed this way, we are doing from scratch so we require to create database configuration file that way we can use that file in many other file. so let's create api directory and create db_config.php file in api directory and put bellow code:

api/db_config.php

<?php

$hostName = "localhost";

$username = "root";

$password = "root";

$dbname = "blog2";

$mysqli = new mysqli($hostName, $username, $password, $dbname);

?>

In Above file please make sure to check your database configuration because could problem you find somewhere. that's way i tell you check it two times. It was just for your kind information.

Step 2: Create Index Page

Ok, now we also require to create index.php file in our root directory. In this file i added "url" variable in js for site root URL. You can update also with your site URL. so let's create index.php file and put bellow content in that file.

index.php

<!DOCTYPE html>

<html>

<head>

<title>PHP Jquery Ajax CRUD Example</title>

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.min.js"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twbs-pagination/1.3.1/jquery.twbsPagination.min.js"></script>

<script src="https://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/item-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>

</div>

<div class="pull-right">

<button type="button" class="btn btn-success" data-toggle="modal" data-target="#create-item">

Create Item

</button>

</div>

</div>

</div>


<table class="table table-bordered">

<thead>

<tr>

<th>Title</th>

<th>Description</th>

<th width="200px">Action</th>

</tr>

</thead>

<tbody>

</tbody>

</table>


<ul id="pagination" class="pagination-sm"></ul>


<!-- Create Item Modal -->

<div class="modal fade" id="create-item" 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 Item</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="title">Title:</label>

<input type="text" name="title" class="form-control" data-error="Please enter title." required />

<div class="help-block with-errors"></div>

</div>


<div class="form-group">

<label class="control-label" for="title">Description:</label>

<textarea name="description" class="form-control" data-error="Please enter description." 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 Item Modal -->

<div class="modal fade" id="edit-item" 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 Item</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="title">Title:</label>

<input type="text" name="title" class="form-control" data-error="Please enter title." required />

<div class="help-block with-errors"></div>

</div>


<div class="form-group">

<label class="control-label" for="title">Description:</label>

<textarea name="description" class="form-control" data-error="Please enter description." 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: Create CRUD JS File

In this step we will create jquery file and write ajax request code on it. So first create js folder on your root directory and then create item-ajax.js file on it.

js/item-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/getData.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/getData.php',

data: {page:page}

}).done(function(data){

manageRow(data.data);

});

}


/* Add new Item table row */

function manageRow(data) {

var rows = '';

$.each( data, function( key, value ) {

rows = rows + '<tr>';

rows = rows + '<td>'+value.title+'</td>';

rows = rows + '<td>'+value.description+'</td>';

rows = rows + '<td data-id="'+value.id+'">';

rows = rows + '<button data-toggle="modal" data-target="#edit-item" class="btn btn-primary edit-item">Edit</button> ';

rows = rows + '<button class="btn btn-danger remove-item">Delete</button>';

rows = rows + '</td>';

rows = rows + '</tr>';

});


$("tbody").html(rows);

}


/* Create new Item */

$(".crud-submit").click(function(e){

e.preventDefault();

var form_action = $("#create-item").find("form").attr("action");

var title = $("#create-item").find("input[name='title']").val();

var description = $("#create-item").find("textarea[name='description']").val();


if(title != '' && description != ''){

$.ajax({

dataType: 'json',

type:'POST',

url: url + form_action,

data:{title:title, description:description}

}).done(function(data){

$("#create-item").find("input[name='title']").val('');

$("#create-item").find("textarea[name='description']").val('');

getPageData();

$(".modal").modal('hide');

toastr.success('Item Created Successfully.', 'Success Alert', {timeOut: 5000});

});

}else{

alert('You are missing title or description.')

}


});


/* Remove Item */

$("body").on("click",".remove-item",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('Item Deleted Successfully.', 'Success Alert', {timeOut: 5000});

getPageData();

});


});


/* Edit Item */

$("body").on("click",".edit-item",function(){


var id = $(this).parent("td").data('id');

var title = $(this).parent("td").prev("td").prev("td").text();

var description = $(this).parent("td").prev("td").text();


$("#edit-item").find("input[name='title']").val(title);

$("#edit-item").find("textarea[name='description']").val(description);

$("#edit-item").find(".edit-id").val(id);


});


/* Updated new Item */

$(".crud-submit-edit").click(function(e){


e.preventDefault();

var form_action = $("#edit-item").find("form").attr("action");

var title = $("#edit-item").find("input[name='title']").val();


var description = $("#edit-item").find("textarea[name='description']").val();

var id = $("#edit-item").find(".edit-id").val();


if(title != '' && description != ''){

$.ajax({

dataType: 'json',

type:'POST',

url: url + form_action,

data:{title:title, description:description,id:id}

}).done(function(data){

getPageData();

$(".modal").modal('hide');

toastr.success('Item Updated Successfully.', 'Success Alert', {timeOut: 5000});

});

}else{

alert('You are missing title or description.')

}


});

});

Step 4: Create AJAX File

In this step we require to create api file for getting item Data, Add item Data, update item Data and delete item Data. So let's create api file one by one.

api/getData.php

<?php

require 'db_config.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 items";

$sql = "SELECT * FROM items Order By id desc LIMIT $start_from, $num_rec_per_page";


$result = $mysqli->query($sql);


while($row = $result->fetch_assoc()){


$json[] = $row;


}


$data['data'] = $json;


$result = mysqli_query($mysqli,$sqlTotal);


$data['total'] = mysqli_num_rows($result);


echo json_encode($data);


?>

api/create.php

<?php


require 'db_config.php';


$post = $_POST;


$sql = "INSERT INTO items (title,description)


VALUES ('".$post['title']."','".$post['description']."')";


$result = $mysqli->query($sql);


$sql = "SELECT * FROM items Order by id desc LIMIT 1";


$result = $mysqli->query($sql);


$data = $result->fetch_assoc();


echo json_encode($data);


?>

api/update.php

<?php


require 'db_config.php';


$id = $_POST["id"];

$post = $_POST;


$sql = "UPDATE items SET title = '".$post['title']."'

,description = '".$post['description']."'

WHERE id = '".$id."'";


$result = $mysqli->query($sql);


$sql = "SELECT * FROM items WHERE id = '".$id."'";


$result = $mysqli->query($sql);


$data = $result->fetch_assoc();


echo json_encode($data);


?>

api/delete.php

<?php


require 'db_config.php';


$id = $_POST["id"];


$sql = "DELETE FROM items WHERE id = '".$id."'";


$result = $mysqli->query($sql);


echo json_encode([$id]);


?>

Ok now we are ready to run this example by following command:

php -S localhost:8000

Check on Browser URL like as bellow:

http://localhost:8000

I hope it can help you...

Shares