PHP CRUD Operation Using Ajax and JQuery Example

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

Today, I want to share with you PHP Mysql CRUD using Jquery Ajax from scratch. CRUD stands for Create, Read, Update and Delete database data. Add, Edit, Update, and Delete functionality is used almost every PHP application. But today i will show you very simple way to crud using bootstrap model.

In this tutorial we will do insert, update and delete task for items. In this example i also use bootstrap for layout. I write just few step to follow you can make simple crud application with jquery pagination in your laravel 5 project.

In this example i used several jquery Plugin for fire Ajax, Ajax pagination, Bootstrap, Bootstrap Validation, notification as listed bellow.

1.Jquery

2.Bootstrap

3.twbsPagination js

4.Validator JS(Bootstrap form validation example with demo using validator.js plugin)

5.toastr JS(Jquery notification popup box example using toastr JS plugin with demo)

this simple ajax crud example, i created "Item Management" with you can do several option like as bellow:

1. Item Listing

2. Item Create

3. Item Edit

4. Item Delete

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 items table and DB Config file

In first step 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,

`created_at` timestamp NULL DEFAULT NULL,

`updated_at` timestamp NULL DEFAULT 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 configration 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

define (DB_USER, "root");

define (DB_PASSWORD, "root");

define (DB_DATABASE, "h_blog");

define (DB_HOST, "localhost");

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

?>

In Above file please make sure to check your batabase 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.php File

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 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 API 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]);


?>

Step 5: Run Example

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...

Video

Shares