Home JavaScript

AJAX CRUD Tutorial Using jQuery, JSON and PHP – Step by Step Guide!


Previously, we learned how to create a simple REST API in PHP. Today, we are going to learn how to create or insert, read, update and delete records with our AJAX CRUD Tutorial. We will use jQuery, JSON and PHP.

Contents of this tutorial include:

1.0 Tutorial Overview
2.0 Program Output1
3.0 Set Up The REST API

4.0 Basic Files & Folders
4.1 File Structure
4.2 Create index.html file
4.3 Enable Bootstrap
4.4 Create custom CSS file
4.5 Download jQuery library and Bootbox
4.6 Create app.js file
4.7 Create “products” scripts
4.8 Output

5.0 How To Read JSON Data Using jQuery AJAX?
5.1 Show products on first page load
5.2 Show products on click of a button
5.3 Create showProducts() function
5.4 Get list of products
5.5 Add “Create Product” button
5.6 Build HTML table
5.7 Build table row per record
5.8 Inject to page content
5.9 Change page title
5.10 Output

6.0 How To Create or Insert Data Using jQuery AJAX?
6.1 Handle “Create Product” Button Click
6.2 Get list of categories from API
6.3 Build “categories option” select field
6.4 Add “Read Products” button
6.5 Build “Create Product” HTML Form
6.6 Show “Create Product” form and change page title
6.7 Handle “create product” form submit
6.8 Get form data
6.9 Send data to server
6.10 Output

7.0 How To Read One Data Using jQuery AJAX?
7.1 Handle “read one” button click
7.2 Get product ID
7.3 Read one record from API
7.4 Add “read products” button
7.5 Show record data in HTML table
7.6 Show “Read One Product” HTML table and change page title
7.7 Output

8.0 How To Update Data Using jQuery AJAX?
8.1 Handle “udpate product” button click
8.2 Get product ID
8.3 Read product information
8.4 Get list of categories
8.5 Add “Read Products” button
8.6 Build “Update Product” form
8.7 Show “Update Product” form and change page title
8.8 Handle “udpate product” form submission
8.9 Get form data
8.10 Send form data to server
8.11 Output

9.0 How To Delete Data Using jQuery AJAX?
9.1 Handle “Delete Product” button click
9.2 Get product ID
9.3 Show “delete confirmation” dialog box
9.4 Delete record using API
9.5 Output

10.0 How To Search Data Using jQuery AJAX?
10.1 Include two JS file in index.html
10.2 Create products.js file
10.3 Create search-product.js file
10.4 Change read-products.js
10.5 Output

11.0 How To Paginate Data Using jQuery AJAX?
11.1 Change JSON URL
11.2 Show products using JSON URL
11.3 Add Pagination HTML
11.5 Output

12.0 How To Run The Source Code?
13.0 Download LEVEL 1 Source Code
14.0 Download LEVEL 2 Source Code
15.0 Download LEVEL 3 Source Code
16.0 Download ALL LEVELS

17.0 What’s Next?
18.0 Related Tutorials
19.0 Notes

Before we start, we want to let you know that your feedback is important to us!

If there's a section in this tutorial that is confusing or hard to understand, we consider it as a problem. Please let us know. We will solve this problem within 24 hours.

Send a detailed description of the problem to my email to mike@codeofaninja.com today. Use "codeofaninja.com improvement" as the subject of your email. Thank you!

1.0 Overview

What is AJAX? It stands for “Asynchronous JavaScript and XML“.

I’ll try to explain it in the simplest way: Using AJAX will prevent re-loading the whole page for every button click you make. As a result, it makes the user experience better. Your web app will be faster.

Ajax is not a technology, but a group of technologies. This can include HTML, CSS, JavaScript and server side scripting like PHP.

I highly recommend studying the previous tutorials first before proceeding here. But if you think you can take this one, then go on.

This tutorial will focus on creating, reading, updating and deleting database records. We will do it using a jQuery, JSON and PHP.

jQuery will help us with the AJAX part. JSON data will be handled by the REST API built using PHP.

2.0 Program Output – PHP AJAX CRUD Tutorial

Below are some screenshots of our script’s output. You can click an image to view the larger version of it. Use the left and right arrow to navigate through the screenshots.

2.1 LEVEL 1 Source Code Output


2.2 LEVEL 2 Source Code Output


2.3 LEVEL 3 Source Code Output


The LEVEL 2 and 3 source code outputs proves that you can add and customize more features. It’s easier and faster if you will learn by following our tutorial below.

Downloading our source codes is your huge advantage as well. For now, let’s proceed to the step by step tutorial of our LEVEL 1 source code. Enjoy!

3.0 Set Up The REST API

In this tutorial, we are going to use a REST API built with PHP.

We did not include REST API source code because we want you to focus on learning how to code with AJAX, not PHP.

But the good news is, we made a separate tutorial about how to build a simple REST API with PHP. Click here to learn the step-by-step PHP REST API tutorial.

I highly recommend learning our REST API tutorial first. This is because we are going to use that API for the rest of this tutorial.

But if you already have your own REST API that will work with this tutorial, that’s okay as well.

In my case, one example where I can access the REST API is: http://localhost/api/product/read.php

That link will show me the list of products from the database, in JSON format. It looks like the following screenshot.

The data above will be consumed by our AJAX app. The list of products will be displayed in Bootstrap table with buttons like “Read One”, “Update” and “Delete”. You will see it in the “How To Read JSON Data Using jQuery AJAX?” section of this tutorial.

By the way, I’m using a Chrome extension called JSONView to make the JSON data readable in the browser.

4.0 Basic Files & Folders

4.1 File Structure

We will have the following files and folders at the end of this LEVEL 1 source code tutorial.

├─ app/
├─── assets/
├────── css/
├───────── style.css
├────── js/
├───────── bootbox.min.js
├───────── jquery.js
├─── products/
├────── create-product.js
├────── delete-product.js
├────── read-one-product.js
├────── read-products.js
├────── update-product.js
├─── app.js
├─ index.html

On the next sections, we will start creating the files and folders to achieve the one above.

4.2 Create index.html file

Create index.html file on your project’s main folder. Open that file and put the following code.

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Read Products</title>

    <!-- bootstrap CSS -->
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

	<!-- custom CSS -->
	<link href="app/assets/css/style.css" rel="stylesheet" />

</head>
<body>

<!-- our app will be injected here -->
<div id="app"></div>

<!-- jQuery library -->
<script src="app/assets/js/jquery.js"></script>

<!-- bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<!-- bootbox for confirm pop up -->
<script src="app/assets/js/bootbox.min.js"></script>

<!-- app js script -->
<script src="app/app.js"></script>

<!-- products scripts -->
<script src="app/products/read-products.js"></script>
<script src="app/products/create-product.js"></script>
<script src="app/products/read-one-product.js"></script>
<script src="app/products/update-product.js"></script>
<script src="app/products/delete-product.js"></script>

</body>
</html>

4.3 Enable Bootstrap

As you can see in the index.html file above, we enabled Bootstrap via CDN.

If you need to enable Bootstrap via download, that will work as well.

See this tutorial to help you do that.

4.4 Create custom CSS file

  1. Create “app” folder.
  2. Open the “app” folder and create the “assets” folder.
  3. Open the “assets” folder and create the “css” folder.
  4. Open the “css” folder and create “style.css” file.

The “style.css” file is our custom CSS file. You can put any CSS in this file for additional web page styling. In our case, we have the following CSS code inside the “style.css” file.

.m-r-10px{ margin-right:10px; }
.m-b-10px{ margin-bottom:10px; }
.m-b-15px{ margin-bottom:15px; }
.m-b-20px{ margin-bottom:20px; }
.w-5-pct{ width:5%; }
.w-10-pct{ width:10%; }
.w-15-pct{ width:15%; }
.w-20-pct{ width:20%; }
.w-25-pct{ width:25%; }
.w-30-pct{ width:30%; }
.w-35-pct{ width:35%; }
.w-40-pct{ width:40%; }
.w-45-pct{ width:45%; }
.w-50-pct{ width:50%; }
.w-55-pct{ width:55%; }
.w-60-pct{ width:60%; }
.w-65-pct{ width:65%; }
.w-70-pct{ width:70%; }
.w-75-pct{ width:75%; }
.w-80-pct{ width:80%; }
.w-85-pct{ width:85%; }
.w-90-pct{ width:90%; }
.w-95-pct{ width:95%; }
.w-100-pct{ width:100%; }
.display-none{ display:none; }
.padding-bottom-2em{ padding-bottom:2em; }
.width-30-pct{ width:30%; }
.width-40-pct{ width:40%; }
.overflow-hidden{ overflow:hidden; }
.margin-right-1em{ margin-right:1em; }
.right-margin{ margin:0 .5em 0 0; }
.margin-bottom-1em { margin-bottom:1em; }
.margin-zero{ margin:0; }
.text-align-center{ text-align:center; }

4.5 Download jQuery and Bootbox.js libraries

  1. Open “app” folder.
  2. Open “assets” folder inside “app” folder
  3. Create “js” folder inside “assets” folder.

The “js” folder is where we will put the jQuery and Bootbox.js libraries.

jQuery JavaScript library is needed to make our simple app simple. Download jQuery in this link.

Bootbox.js library is needed to make the “delete” confirmation dialog box look better. Download Bootbox.js in this link.

There are CDNs for these JavaScript libraries as well. You can use them if you want but I prefer the downloaded versions. Both will work.

4.6 Create app.js file

The “app.js” file contains some basic HTML and JavaScript functions that can be used by other JS files in our app.

  1. Open “app” folder.
  2. Inside that “app” folder, create “app.js” file.
  3. Open “app.js” file and put the following code.
$(document).ready(function(){

    // app html
    app_html="";

    app_html+="<div class='container'>";

    	app_html+="<div class='page-header'>";
    		app_html+="<h1 id='page-title'>Read Products</h1>";
    	app_html+="</div>";

    	// this is where the contents will be shown.
    	app_html+="<div id='page-content'></div>";

    app_html+="</div>";

    // inject to 'app' in index.html
    $("#app").html(app_html);

});

// change page title
function changePageTitle(page_title){

	// change page title
	$('#page-title').text(page_title);

	// change title tag
	document.title=page_title;
}

// function to make form values to json format
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

4.7 Create “products” scripts

Now, we will create several JavaScript files.

  1. Open “app” folder.
  2. Create “products” folder inside “app” folder.
  3. Create the following files inside “products” folder:
    • read-products.js
    • create-product.js
    • read-one-product.js
    • update-product.js
    • delete-product.js

What’s the code inside the JavaScript files above? For now, we will leave them empty. But we will fill them out on the next several sections of this tutorial.

4.8 Output

Our code so far will have almost empty output. It should look like the following.

5.0 How To Read JSON Data Using jQuery AJAX?

5.1 Show products on first page load

  1. Open “app” folder.
  2. Open “products” folder inside the “app” folder.
  3. Open read-products.js file inside the “products” folder.

The following code will call the showProducts() method on first load of the web page.

The showProducts() will show the list of products in an HTML table. Put the following code inside read-products.js file.

$(document).ready(function(){

    // show list of product on first load
    showProducts();

});

// showProducts() method will be here

5.2 Show products on click of a button

The following code will call showProducts() method in click of a button with “read-products-button” class.

The button can be found in the “create product” and “update product” HTML template. We will see it in the next sections.

Put the following code under the showProducts(); of the previous section.

// when a 'read products' button was clicked
$(document).on('click', '.read-products-button', function(){
	showProducts();
});

5.3 Create showProducts() function

Now we will create the showProducts() method. Replace “// showProducts() method will be here” comment above – with the following code.

// function to show list of products
function showProducts(){

}

5.4 Get list of products

The following code will contact our API to get the list of products in JSON format. Put the following code after the opening curly brace of the previous section.

// get list of products from the API
$.getJSON("http://localhost/api/product/read.php", function(data){

});

5.5 Add “Create Product” button

We have to add a “Create Product” button in the “products list” view. We will make this button work later in this tutorial.

Place the following code after the opening curly brace of the previous section.

// html for listing products
read_products_html="";

// when clicked, it will load the create product form
read_products_html+="<div id='create-product' class='btn btn-primary pull-right m-b-15px create-product-button'>";
	read_products_html+="<span class='glyphicon glyphicon-plus'></span> Create Product";
read_products_html+="</div>";

5.6 Build HTML table

We have to start building the HTML table where the list of products will appear.

The following code will build an HTML table with its heading. Place it after the previous section’s code.

// start table
read_products_html+="<table class='table table-bordered table-hover'>";

	// creating our table heading
	read_products_html+="<tr>";
		read_products_html+="<th class='w-25-pct'>Name</th>";
		read_products_html+="<th class='w-10-pct'>Price</th>";
		read_products_html+="<th class='w-15-pct'>Category</th>";
		read_products_html+="<th class='w-25-pct text-align-center'>Action</th>";
	read_products_html+="</tr>";
	
	// rows will be here

// end table
read_products_html+="</table>";

5.7 Build table row per record

We will loop through each record returned by the API. In each record, we will create a table row.

Aside from product data, the table row will have the “action” buttons as well. These include the “Read One”, “Edit” and “Delete” buttons.

Replace “// rows will be here” comment of the previous section with the following code.

// loop through returned list of data
$.each(data.records, function(key, val) {

	// creating new table row per record
	read_products_html+="<tr>";

		read_products_html+="<td>" + val.name + "</td>";
		read_products_html+="<td>$" + val.price + "</td>";
		read_products_html+="<td>" + val.category_name + "</td>";

		// 'action' buttons
		read_products_html+="<td>";
			// read one product button
			read_products_html+="<button class='btn btn-primary m-r-10px read-one-product-button' data-id='" + val.id + "'>";
				read_products_html+="<span class='glyphicon glyphicon-eye-open'></span> Read";
			read_products_html+="</button>";

			// edit button
			read_products_html+="<button class='btn btn-info m-r-10px update-product-button' data-id='" + val.id + "'>";
				read_products_html+="<span class='glyphicon glyphicon-edit'></span> Edit";
			read_products_html+="</button>";

			// delete button
			read_products_html+="<button class='btn btn-danger delete-product-button' data-id='" + val.id + "'>";
				read_products_html+="<span class='glyphicon glyphicon-remove'></span> Delete";
			read_products_html+="</button>";
		read_products_html+="</td>";

	read_products_html+="</tr>";

});

5.8 Inject to page content

We have to make the HTML table appear on our webpage. We will do this by injecting the table to the “page-content” div.

Place the following code after the closing “table” tag

// inject to 'page-content' of our app
$("#page-content").html(read_products_html);

5.9 Change page title

The following code will change the “title” seen on the web page and the “title” seen on the browser tab.

Place the following code after the previous section’s code.

// chage page title
changePageTitle("Read Products");

5.10 Output

After doing all the steps above, output should look like the following.

6.0 How To Create or Insert Data Using jQuery AJAX?

6.1 Handle “Create Product” Button Click

  1. Open “app” folder.
  2. Open “products” folder inside the “app” folder.
  3. Open create-product.js file inside the “products” folder.

The following code will handle a click of a button. This button should have “create-product-button” class.

Place the following code inside create-product.js file.

$(document).ready(function(){

    // show html form when 'create product' button was clicked
    $(document).on('click', '.create-product-button', function(){
		// categories api call will be here
    });

	// 'create product form' handle will be here
});

6.2 Get list of categories from API

We need to get list of categories from the API because we will build the “categories” select field. This is where the user can select the category of the product.

Replace “// categories api call will be here” of the previous section with the following code.

// load list of categories
$.getJSON("http://localhost/api/category/read.php", function(data){

});

6.3 Build “categories option” select field

This is where we build the HTML “select” field with “categories” option.

Place the following code after the opening curly brace of the previous section.

// build categories option html
// loop through returned list of data
var categories_options_html="";
categories_options_html+="<select name='category_id' class='form-control'>";
$.each(data.records, function(key, val){
	categories_options_html+="<option value='" + val.id + "'>" + val.name + "</option>";
});
categories_options_html+="</select>";

6.4 Add “Read Products” button

The “read products” button is needed so that we can go back to the products list.

Place the following code after the previous section’s code.

// we have our html form here where product information will be entered
// we used the 'required' html5 property to prevent empty fields
var create_product_html="";

// 'read products' button to show list of products
create_product_html+="<div id='read-products' class='btn btn-primary pull-right m-b-15px read-products-button'>";
	create_product_html+="<span class='glyphicon glyphicon-list'></span> Read Products";
create_product_html+="</div>";

6.5 Build “Create Product” HTML Form

Now we will build the actual “creat product” HTML form. This is where the user can enter the new product information that will be sent to the server.

Place the following code after the previous section’s code.

// 'create product' html form
create_product_html+="<form id='create-product-form' action='#' method='post' border='0'>";
	create_product_html+="<table class='table table-hover table-responsive table-bordered'>";

		// name field
		create_product_html+="<tr>";
			create_product_html+="<td>Name</td>";
			create_product_html+="<td><input type='text' name='name' class='form-control' required /></td>";
		create_product_html+="</tr>";

		// price field
		create_product_html+="<tr>";
			create_product_html+="<td>Price</td>";
			create_product_html+="<td><input type='number' min='1' name='price' class='form-control' required /></td>";
		create_product_html+="</tr>";

		// description field
		create_product_html+="<tr>";
			create_product_html+="<td>Description</td>";
			create_product_html+="<td><textarea name='description' class='form-control' required></textarea></td>";
		create_product_html+="</tr>";

		// categories 'select' field
		create_product_html+="<tr>";
			create_product_html+="<td>Category</td>";
			create_product_html+="<td>" + categories_options_html + "</td>";
		create_product_html+="</tr>";

		// button to submit form
		create_product_html+="<tr>";
			create_product_html+="<td></td>";
			create_product_html+="<td>";
				create_product_html+="<button type='submit' class='btn btn-primary'>";
					create_product_html+="<span class='glyphicon glyphicon-plus'></span> Create Product";
				create_product_html+="</button>";
			create_product_html+="</td>";
		create_product_html+="</tr>";

	create_product_html+="</table>";
create_product_html+="</form>";

6.6 Show “Create Product” form and change page title

We have to make the HTML button and form appear on our web page. We will change the page title as well.

Place the following code after the previous section’s code.

// inject html to 'page-content' of our app
$("#page-content").html(create_product_html);

// chage page title
changePageTitle("Create Product");

6.7 Handle “create product” form submit

If the “create product” form is submitted, we need a script to handle it.

Find “// ‘create product form’ handle will be here” and replace it with the following code.

// will run if create product form was submitted
$(document).on('submit', '#create-product-form', function(){
	// form data will be here
});

6.8 Get form data

This is how we get data entered in our “create product” HTML form.

Replace “// form data will be here” of the previous section with the following code.

// get form data
var form_data=JSON.stringify($(this).serializeObject());

6.9 Send data to server

Now we will send the data to the server.

Place the following code after the previous section’s code.

// submit form data to api
$.ajax({
	url: "http://localhost/api/product/create.php",
	type : "POST",
	contentType : 'application/json',
	data : form_data,
	success : function(result) {
		// product was created, go back to products list
		showProducts();
	},
	error: function(xhr, resp, text) {
		// show error to console
		console.log(xhr, resp, text);
	}
});

return false;

6.10 Output

Output should look like the following.

7.0 How To Read One Data Using jQuery AJAX?

7.1 Handle “read one” button click

The “read one” button is seen on the “product list” view. When click, it should show the complete product details.

  1. Open “app” folder.
  2. Inside the “app” folder, open “products” folder.
  3. Inside the “products” folder, open “read-one-product.js” file.

Place the following code inside “read-one-product.js” file.

$(document).ready(function(){

    // handle 'read one' button click
    $(document).on('click', '.read-one-product-button', function(){
		// product ID will be here
    });

});

7.2 Get product ID

Our script need to identify the record to be read. We do it by getting the product ID.

Replace “// product ID will be here” of the previous section with the following code.

// get product id
var id = $(this).attr('data-id');

7.3 Read one record from API

We will send the product ID to the API. It will return the data based on the given ID.

Place the following code after the previous section’s code.

// read product record based on given ID
$.getJSON("http://localhost/api/product/read_one.php?id=" + id, function(data){
	// read products button will be here
});

7.4 Add “read products” button

We need the “read products” button so we can go back to the products list.

Replace “// read products button will be here” of the previous section with the following code.

// start html
var read_one_product_html="";

// when clicked, it will show the product's list
read_one_product_html+="<div id='read-products' class='btn btn-primary pull-right m-b-15px read-products-button'>";
	read_one_product_html+="<span class='glyphicon glyphicon-list'></span> Read Products";
read_one_product_html+="</div>";

7.5 Show record data in HTML table

We will place the product information returned by te API to an HTML table.

Place the following code after the previous section’s code.

// product data will be shown in this table
read_one_product_html+="<table class='table table-bordered table-hover'>";

	// product name
	read_one_product_html+="<tr>";
		read_one_product_html+="<td class='w-30-pct'>Name</td>";
		read_one_product_html+="<td class='w-70-pct'>" + data.name + "</td>";
	read_one_product_html+="</tr>";

	// product price
	read_one_product_html+="<tr>";
		read_one_product_html+="<td>Price</td>";
		read_one_product_html+="<td>" + data.price + "</td>";
	read_one_product_html+="</tr>";

	// product description
	read_one_product_html+="<tr>";
		read_one_product_html+="<td>Description</td>";
		read_one_product_html+="<td>" + data.description + "</td>";
	read_one_product_html+="</tr>";

	// product category name
	read_one_product_html+="<tr>";
		read_one_product_html+="<td>Category</td>";
		read_one_product_html+="<td>" + data.category_name + "</td>";
	read_one_product_html+="</tr>";

read_one_product_html+="</table>";

7.6 Show “Read One Product” HTML table and change page title

We have to make the HTML button and table appear on our web page. We will change the page title as well.

Place the following code after the previous section’s code.

// inject html to 'page-content' of our app
$("#page-content").html(read_one_product_html);

// chage page title
changePageTitle("Create Product");

7.7 Output

Output should look like the following.

8.0 How To Update Data Using jQuery AJAX?

8.1 Handle “udpate product” button click

The “edit” button is seen on the “product list” view. When click, it should show the “update product” form filled-out with product information.

  1. Open “app” folder.
  2. Inside the “app” folder, open “products” folder.
  3. Inside the “products” folder, open “update-product.js” file.

Place the following code inside “update-product.js” file.

$(document).ready(function(){

    // show html form when 'update product' button was clicked
    $(document).on('click', '.update-product-button', function(){
		// product ID will be here
    });
	
	// 'update product form' submit handle will be here
});

8.2 Get product ID

Our script need to identify the record to be read. We do it by getting the product ID.

Replace “// product ID will be here” of the previous section with the following code.

// get product id
var id = $(this).attr('data-id');

8.3 Read product information

To fill out our “update product” HTML form, we need to get product information from the API.

Place the following code after the previous section’s code.

// read one record based on given product id
$.getJSON("http://localhost/api/product/read_one.php?id=" + id, function(data){

	// values will be used to fill out our form
	var name = data.name;
	var price = data.price;
	var description = data.description;
	var category_id = data.category_id;
	var category_name = data.category_name;
	
	// load list of categories will be here
});

8.4 Get list of categories

The list of categories is needed for product’s category options. Category records will be rendered as options in a “select” HTML input field.

Replace “// load list of categories will be here” of the previous section with the following code.

// load list of categories
$.getJSON("http://localhost/api/category/read.php", function(data){

	// build 'categories option' html
	// loop through returned list of data
	var categories_options_html="";
	categories_options_html+="<select name='category_id' class='form-control'>";

	$.each(data.records, function(key, val){
		
		// pre-select option is category id is the same
		if(val.id==category_id){
			categories_options_html+="<option value='" + val.id + "' selected>" + val.name + "</option>";
		}

		else{
			categories_options_html+="<option value='" + val.id + "'>" + val.name + "</option>";
		}
	});
	categories_options_html+="</select>";
	
	// update product html will be here
});

8.5 Add “Read Products” button

The “read products” button is needed so that we can go back to the products list.

Replace “// update product html will be here” of the previous section with the following code.

// store 'update product' html to this variable
var update_product_html="";

// 'read products' button to show list of products
update_product_html+="<div id='read-products' class='btn btn-primary pull-right m-b-15px read-products-button'>";
	update_product_html+="<span class='glyphicon glyphicon-list'></span> Read Products";
update_product_html+="</div>";

8.6 Build “Update Product” form

Now we will build the “udpate product” HTML form. This form will be built with an HTML table and the input fields are filled-out with product information.

Place the following code after the previous section’s code.

// build 'update product' html form
// we used the 'required' html5 property to prevent empty fields
update_product_html+="<form id='update-product-form' action='#' method='post' border='0'>";
	update_product_html+="<table class='table table-hover table-responsive table-bordered'>";

		// name field
		update_product_html+="<tr>";
			update_product_html+="<td>Name</td>";
			update_product_html+="<td><input value=\"" + name + "\" type='text' name='name' class='form-control' required /></td>";
		update_product_html+="</tr>";

		// price field
		update_product_html+="<tr>";
			update_product_html+="<td>Price</td>";
			update_product_html+="<td><input value=\"" + price + "\" type='number' min='1' name='price' class='form-control' required /></td>";
		update_product_html+="</tr>";

		// description field
		update_product_html+="<tr>";
			update_product_html+="<td>Description</td>";
			update_product_html+="<td><textarea name='description' class='form-control' required>" + description + "</textarea></td>";
		update_product_html+="</tr>";

		// categories 'select' field
		update_product_html+="<tr>";
			update_product_html+="<td>Category</td>";
			update_product_html+="<td>" + categories_options_html + "</td>";
		update_product_html+="</tr>";

		update_product_html+="<tr>";

			// hidden 'product id' to identify which record to delete
			update_product_html+="<td><input value=\"" + id + "\" name='id' type='hidden' /></td>";

			// button to submit form
			update_product_html+="<td>";
				update_product_html+="<button type='submit' class='btn btn-info'>";
					update_product_html+="<span class='glyphicon glyphicon-edit'></span> Update Product";
				update_product_html+="</button>";
			update_product_html+="</td>";

		update_product_html+="</tr>";

	update_product_html+="</table>";
update_product_html+="</form>";

8.7 Show “Update Product” form and change page title

We need to show our “update product” HTML on our webpage. We will change the page title as well.

Put the following code after the previous section’s code.

// inject to 'page-content' of our app
$("#page-content").html(update_product_html);

// chage page title
changePageTitle("Update Product");

8.8 Handle “udpate product” form submission

If the “update product” form is submitted, we need a script to handle it.

Find “// ‘update product form’ submit handle will be here” and replace it with the following code.

// will run if 'create product' form was submitted
$(document).on('submit', '#update-product-form', function(){
	
	// get form data will be here 
	
	return false;
});

8.9 Get form data

We will get the product information from our “update product” HTML form.

Replace “// get form data will be here” of the previous section with the following code.

// get form data
var form_data=JSON.stringify($(this).serializeObject());

8.10 Send form data to server

After getting the form data, we will send the data to our API.

Place the following code after the previous section’s code.

// submit form data to api
$.ajax({
	url: "http://localhost/api/product/update.php",
	type : "POST",
	contentType : 'application/json',
	data : form_data,
	success : function(result) {
		// product was created, go back to products list
		showProducts();
	},
	error: function(xhr, resp, text) {
		// show error to console
		console.log(xhr, resp, text);
	}
});

8.11 Output

Output should look like the following.

9.0 How To Delete Data Using jQuery AJAX?

9.1 Handle “Delete Product” button click

The “delete product” button is seen in the “read products” view. When it was clicked, we need to handle it.

  1. Open “app” folder.
  2. Inside the “app” folder, open “products” folder.
  3. Inside the “products” folder, open “delete-product.js” file.

Place the following code inside “delete-product.js” file.

$(document).ready(function(){

    // will run if the delete button was clicked
    $(document).on('click', '.delete-product-button', function(){
		// product id will be here
	});
});

9.2 Get product ID

The product ID is needed to identify which record to delete using the API.

Replace “// product id will be here” of the previous section with the following code.

// get the product id
var product_id = $(this).attr('data-id');

9.3 Show “delete confirmation” dialog box

This is where we will use the Bootbox.js library. We will show a dialog box with “Are you sure?” message with “Yes” and “No” buttons.

Place the following code after the previous section’s code.

// bootbox for good looking 'confirm pop up'
bootbox.confirm({

	message: "<h4>Are you sure?</h4>",
	buttons: {
		confirm: {
			label: '<span class="glyphicon glyphicon-ok"></span> Yes',
			className: 'btn-danger'
		},
		cancel: {
			label: '<span class="glyphicon glyphicon-remove"></span> No',
			className: 'btn-primary'
		}
	},
	callback: function (result) {
		// delete request will be here
	}
});

9.4 Delete record using API

If the user clicked “Yes” on the dialog box, a “delete” request will be sent to the API.

Replace “// delete request will be here” of the previous section with the following code.

 if(result==true){

	// send delete request to api / remote server
	$.ajax({
		url: "http://localhost/api/product/delete.php",
		type : "POST",
		dataType : 'json',
		data : JSON.stringify({ id: product_id }),
		success : function(result) {

			// re-load list of products
			showProducts();
		},
		error: function(xhr, resp, text) {
			console.log(xhr, resp, text);
		}
	});

}

9.5 Output

10.0 How To Search Data Using jQuery AJAX?

This feature is part of our LEVEL 2 source code.

10.1 Include two JS file in index.html

<!-- products scripts -->
<script src="app/products/products.js"></script>
<script src="app/products/search-product.js"></script>

10.2 Create products.js file

The “products.js” file will contain any functions that can be used by other product components like our “read-products.js” or “search-products.js” files.

Open “app” folder. Open “products” folder. Create “products.js” file.

Open the “products.js” file and put the following code.

// product list html
function readProductsTemplate(data, keywords){

    var read_products_html="";

    // search products form
    read_products_html+="<form id='search-product-form' action='#' method='post'>";
    read_products_html+="<div class='input-group pull-left w-30-pct'>";

        read_products_html+="<input type='text' value=\"" + keywords + "\" name='keywords' class='form-control product-search-keywords' placeholder='Search products...' />";

        read_products_html+="<span class='input-group-btn'>";
            read_products_html+="<button type='submit' class='btn btn-default' type='button'>";
                read_products_html+="<span class='glyphicon glyphicon-search'></span>";
            read_products_html+="</button>";
        read_products_html+="</span>";

    read_products_html+="</div>";
    read_products_html+="</form>";

    // when clicked, it will load the create product form
    read_products_html+="<div id='create-product' class='btn btn-primary pull-right m-b-15px create-product-button'>";
        read_products_html+="<span class='glyphicon glyphicon-plus'></span> Create Product";
    read_products_html+="</div>";

    // start table
    read_products_html+="<table class='table table-bordered table-hover'>";

        // creating our table heading
        read_products_html+="<tr>";
            read_products_html+="<th class='w-25-pct'>Name</th>";
            read_products_html+="<th class='w-10-pct'>Price</th>";
            read_products_html+="<th class='w-15-pct'>Category</th>";
            read_products_html+="<th class='w-25-pct text-align-center'>Action</th>";
        read_products_html+="</tr>";

    // loop through returned list of data
    $.each(data.records, function(key, val) {

        // creating new table row per record
        read_products_html+="<tr>";

            read_products_html+="<td>" + val.name + "</td>";
            read_products_html+="<td>$" + val.price + "</td>";
            read_products_html+="<td>" + val.category_name + "</td>";

            // 'action' buttons
            read_products_html+="<td>";
                // read product button
                read_products_html+="<button class='btn btn-primary m-r-10px read-one-product-button' data-id='" + val.id + "'>";
                    read_products_html+="<span class='glyphicon glyphicon-eye-open'></span> Read";
                read_products_html+="</button>";

                // edit button
                read_products_html+="<button class='btn btn-info m-r-10px update-product-button' data-id='" + val.id + "'>";
                    read_products_html+="<span class='glyphicon glyphicon-edit'></span> Edit";
                read_products_html+="</button>";

                // delete button
                read_products_html+="<button class='btn btn-danger delete-product-button' data-id='" + val.id + "'>";
                    read_products_html+="<span class='glyphicon glyphicon-remove'></span> Delete";
                read_products_html+="</button>";
            read_products_html+="</td>";

        read_products_html+="</tr>";

    });

    // end table
    read_products_html+="</table>";

    // inject to 'page-content' of our app
    $("#page-content").html(read_products_html);
}

10.3 Create search-product.js file

The “search-product.js” file will contain a code that catches the submission of “search product” form.

Open “app” folder. Open “products” folder. Create “search-products.js” file.

Open the “search-products.js” file and put the following code.

$(document).ready(function(){

    // when a 'search products' button was clicked
    $(document).on('submit', '#search-product-form', function(){

        // get search keywords
        var keywords = $(this).find(":input[name='keywords']").val();

        // get data from the api based on search keywords
        $.getJSON("http://localhost/api/product/search.php?s=" + keywords, function(data){

            // template in products.js
            readProductsTemplate(data, keywords);

            // chage page title
            changePageTitle("Search products: " + keywords);

        });

        // prevent whole page reload
        return false;
    });

});

10.4 Change read-products.js

We want the “product list” and “search product” have the same HTML table template. To do this, we will use the readProductsTemplate() function of products.js file.

Open “app” folder. Open “products” folder. Open “read-products.js’ file. Change the showProducts() function to the following code.

// function to show list of products
function showProducts(){

    // get list of products from the API
    $.getJSON("http://localhost/api/product/read.php", function(data){

        // html for listing products
        readProductsTemplate(data, "");

        // chage page title
        changePageTitle("Read Products");

    });
}

10.5 Output

11.0 How To Paginate Data Using jQuery AJAX?

This feature is part of our LEVEL 2 and LEVEL 3 source codes.

11.1 Change JSON URL

To make pagination work, we’ll have to change the JSON URL. The contents of this new JSON data will include the “paging” node. It looks like the following.

So we will change the JSON URL from:

http://localhost/api/product/read.php

to

http://localhost/api/product/read_paging.php

It means we have to change something on our code. See the change in the next section.

11.2 Show products using JSON URL

Open /app/products/read-products.js file. Replace the code with the following.

$(document).ready(function(){

    // show list of product on first load
    showProductsFirstPage();

    // when a 'read products' button was clicked
    $(document).on('click', '.read-products-button', function(){
        showProductsFirstPage();
    });

    // when a 'page' button was clicked
    $(document).on('click', '.pagination li', function(){
        // get json url
        var json_url=$(this).find('a').attr('data-page');

        // show list of products
        showProducts(json_url);
    });


});

function showProductsFirstPage(){
    var json_url="http://localhost/api/product/read_paging.php";
    showProducts(json_url);
}

// function to show list of products
function showProducts(json_url){

    // get list of products from the API
    $.getJSON(json_url, function(data){

        // html for listing products
        readProductsTemplate(data, "");

        // chage page title
        changePageTitle("Read Products");

    });
}

11.3 Add Pagination HTML

Open /app/products/products.js file. Find the ending “table” tag and put the following code under it.

// pagination
if(data.paging){
    read_products_html+="<ul class='pagination pull-left margin-zero padding-bottom-2em'>";

        // first page
        if(data.paging.first!=""){
            read_products_html+="<li><a data-page='" + data.paging.first + "'>First Page</a></li>";
        }

        // loop through pages
        $.each(data.paging.pages, function(key, val){
            var active_page=val.current_page=="yes" ? "class='active'" : "";
            read_products_html+="<li " + active_page + "><a data-page='" + val.url + "'>" + val.page + "</a></li>";
        });

        // last page
        if(data.paging.last!=""){
            read_products_html+="<li><a data-page='" + data.paging.last + "'>Last Page</a></li>";
        }
    read_products_html+="</ul>";
}

11.5 Output

After making the changes above, run index.html again. Do a hard refresh. You should see the paging buttons like the one below.

12.0 How To Run The Source Code?

We highly recommend for you to follow and study our well-detailed, step-by-step tutorial above first. Nothing beats experience when it comes to learning.

But we believe you will learn faster if you’ll see the final source code as well. We consider it as your additional guide.

Imagine the value or skill upgrade it can bring you. The additional income you can get from your work, projects or business. The precious time you save. Isn’t that what you want?

By now, you need to download our source codes. To do it, use any download buttons in the next few sections below.

Once you downloaded the source codes, here’s how you can run it.

  1. Extract the files to your server directory.
  2. Set up the “api” by following the README.txt inside the “api” folder.
  3. Open your browser and run index.html
  4. If you can see the list of “product” records, it means your set up is correct.

13.0 Download LEVEL 1 Source Code

FEATURES LEVEL 1
Create product YES
Read product YES
Read one product YES
Update product YES
Delete product YES
Bootstrap UI YES
PHP REST API source code YES
FREE email support for 3 months YES
Source code updates via email YES
Download Now

14.0 Download LEVEL 2 Source Code

FEATURES LEVEL 2
All features of LEVEL 1 YES
Search products YES
Pagination of products & search products YES
Create category YES
Read category YES
Read one category YES
Update category YES
Delete category YES
Search categories YES
Pagination of categories & search categories YES
Navigation bar YES
FREE email support for 6 months YES
Download Now

15.0 Download LEVEL 3 Source Code

FEATURES LEVEL 3
All features of LEVEL 2 YES
Inline editing of products & categories YES
Export CSV of products & categories YES
Bootstrap tooltip on some products & categories buttons YES
FREE email support for 1 year YES
Download Now

16.0 Download ALL LEVELS

This means you will download the LEVEL 1, 2 and 3 source codes in separate packages. Select “ALL LEVELS” below and then you click the “Download Now” button.

Download Now

Do you need more reasons to download it?

MORE REASONS TO DOWNLOAD THE CODE ALL
Use new skills for your multiple projects YES
Save huge amount of time learning jQuery AJAX YES
Code examples are direct to the point YES
Well explained and commented source code YES
Fast and friendly email support YES
Free source code updates YES

17.0 What’s Next?

Learn more JavaScript programming with our React CRUD Tutorial – Step By Step Guide!

18.0 Related Tutorials

19.0 Some Notes

#1 Found An Issue?

If you found a problem with this code, we can solve it faster via Email or FB message, please send me a message via email mike@codeofaninja.com, or via our official Facebook page!

Please be more detailed about your issue. Best if you can provide an error message and your test or page URL. Thanks!

Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code.

#2 Become a true Ninja!

We constantly add new tutorials and improve our existing tutorials and source codes. Be one of the first to know an update by subscribing to our FREE newsletter. Get a FREE EBOOK as well. CLICK HERE TO SUBSCRIBE FOR FREE!

#3 Thank You!

Thanks for reading our AJAX CRUD Tutorial Using jQuery, JSON and PHP!