Home Ajax How to create Simple Ajax CRUD using PHP Jquery ?

How to create Simple Ajax CRUD using PHP Jquery ?

by Shahriar Sagor

Today now in this post i want to show you How we can create Simple Ajax CRUD using PHP Jquery ? Here I want to share with you aan example of PHP Mysql CRUD using Jquery Ajax from the scratch. Here CRUD stands for Create, Read, Update and also Delete database data. We know Add, Edit, Update, and Delete functionality is used almost every the PHP application. But today here i will show you a very simple way to crud by using bootstrap model.

Now in this tutorial i will do insert, update and delete task for the items. So in this example i will be also use bootstrap for layout. Here I will write just few step to follow we can make the simple crud application with the jquery pagination in our laravel project.

We can easily implement the crud application from the scratch. so no worry if you can implement it through ny the bellow simple step.

Step 1: Create items table and DB Config file

Now In the first step we need create database and items table. so let’s create the database i did create “new_blog” database and also “items” table inside that database. so you also need to create database as you want but you need to create the “items” table if you are doing from the scratch. so let’s create “items” table by 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 on this way, now we are doing this from the scratch so we need to create database configration file on that way we can use that file in the many other file. so let’s create the api directory and then create db_config.php file in api directory and put the bellow code:

api/db_config.php

<?php
	define (DB_USER, "root");
	define (DB_PASSWORD, "mypassword");
	define (DB_DATABASE, "new_blog");
	define (DB_HOST, "localhost");
	$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
?>

In the Above file please make sure to check that your batabase configuration because it could be problem you find somewhere. So that’s way i am telling you check it two times. And It was a just for your kind information.

Step 2: Create index.php File

Now we also need to create a file as name index.php file in our root directory. Then in this file i will added “url” variable in js for the site root URL. We can also update with our site URL. So let’s create the index.php file and put the 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

Now in this step we need to create jquery file and then write ajax request code on it. So at first need to create js folder on our root directory and then need to 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

Then in this step we need to create the api file for getting item all Data, Add item details Data, update item information Data and delete item Data. So let’s create the 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

Read Also: How to generate PDF from html view file and download using dompdf in laravel?

Good now we are ready to run this example by using the following command:

php -S localhost:8000

Check it on Browser URL like as bellow:

http://localhost:8000

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like