CRUD Application in PHP and Ajax without Page Reload

Using the CRUD application we can Insert (Create), Select (Read), Update and Delete data from the database. If you do not want to refresh the page while doing CRUD operation, you can develop this using Ajax. Ajax makes it easier sometimes because you can do these operations without disturbing other elements on the page.

In this topic, we will develop an application using which users can view the list of products, add new products, update and delete an existing product using Ajax with PHP and MySQL.

You can use it for Admin who can enter products or any items in the system.

make CRUD operations with AJAXFolders and Files

We will be using the below folder structure and files:

write CRUD operations in php and ajax

We have a folder named 'product' under 'xampp/htdocs'.

Folder 'cfg' - This folder is for dbconnect.php which is used to connect to the MySQL database.
Folder 'css' - Our custom stylesheet is in this folder
Folder 'js' - In this folder we have our custom JavaScript file
index.php is the main program that displays a list of products and options to add, update and delete products.
add_product.php, update_product.php and delete_product.php are the php programs which are executed using Ajax call.

Below is the screenshot of the output of index.php

CRUD Operation in PHP Using Ajax, Jquery

In the above screen, you can add a new product, you can also update/delete and existing product. Once a product is added, it will be included in the list. Similarly, if a product is updated, it will be reflected in the product list and when a product is deleted, it will disappear from the list. So, all operations of CRUD are used here using Ajax.

Let us see how we can develop the entire application.

Watch YouTube Video

Create a MySQL table for products

We will create the table named 'product' in MySQL database. This table will have product details, like name, price and stock, etc. The table structure is given below:

PHP CRUD Operations without Page Refresh ajax jQuery

The table has 4 columns.

  1. product_id - It is the unique product_id (primary key) and auto incremented
  2. product_name - Name of the product
  3. price - Price of the product
  4. stock - Available stock

product.sql


CREATE TABLE `product` (
  `product_id` int(11) NOT NULL,
  `product_name` varchar(200) NOT NULL,
  `price` decimal(12,2) NOT NULL,
  `stock` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `product` (`product_id`, `product_name`, `price`, `stock`) VALUES
(1, 'Sofa', '10000.00', 34),
(2, 'Dining Table', '6000.00', 100),
(3, 'Dining Chair(set of 4)', '5000.00', 30),
(4, 'Mattress', '8000.00', 111);

ALTER TABLE `product`
  ADD PRIMARY KEY (`product_id`);

ALTER TABLE `product`
  MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

Connect to MySQL database (dbconnect.php)

We will use the below PHP code to connect to the database. We will include this in other programs to connect to the database.

dbconnect.php


<?php
  $server="localhost";
  $userid="root";
  $pwd="";
  $dbname="test";
  $conn = mysqli_connect($server, $userid, $pwd, $dbname);
//Check connection
if (!$conn) 
  	die("Connection Error: " . mysqli_connect_error());

I am using mysqli_connect() function which needs 4 parameters.

  1. server - localhost
  2. userid - we will use the root user
  3. password - no password for the user root
  4. database name - test database.
For successful connection it will return true. You can also read the topic How to connect to MySQL database in PHP using MySQLi and PDO.

Create Add/Update product forms (index.php)

In index.php, we have an add (Create)form, an update (Update) form and an html table to show the list of existing products (Read). Saving data in the database for add and update forms, is done by a separate PHP program executed using an Ajax request. An overview of index.php is given below:

  1. Show a list of products in an html table.
  2. For each product displayed, show edit and delete links. For updating the product, call the same program (index.php) with the product id and a flag for editing as parameters. This will show the Update form. Call a JavaScript function to delete the product using Ajax.
  3. If the edit flag is set, show the Update Product form
  4. When no flag is set, show add product form
  5. Add, update and delete products are done using individual PHP programs executed using Ajax call.

Display Product List (Read operation)

Let me show the code for displaying list of products in index.php.

PHP AJAX and MySQL crud

It is a simple html table where we display details of each product in a for loop after fetching the data from the database. Let's see the code.


<h4>Product List</h4>
	<div class="table-responsive" id="products">
 		<table class="table table-bordered table-striped">
		 	<tr>
		 		<thead>
		 		<th>Serial No.</th><th>Product Id</th><th>Product Name</th><th>Price (<span class="fa fa-inr"></span>)</th><th>Stock</th><th>Action</th>
		 		</thead>
		 	</tr>	
		 	<?php 
		 	$select = "select * from product order by product_id";
		 	$products = mysqli_query($conn,$select); 
		 	$counter = 0;
		 	if (mysqli_num_rows($products) >0)
		 	 {
			 	foreach ($products as $product_row) { 
			 		$counter++;
			 		$product_id = $product_row['product_id'];
			 		$product_name= $product_row['product_name'];
			 		?>
			 		<tr>
			 			<td><?php echo $counter;?></td>
			 			<td><?php echo $product_row['product_id'];?></td>
			 			<td><?php echo $product_row['product_name'];?></td>
			 			<td><?php echo $product_row['price'];?></td>
			 			<td><?php echo $product_row['stock'];?></td>
			 			<td>
			 				<a class="fa fa-edit" title="Edit" href="index.php?id=<?php echo $product_id;?>&flag=edit"></a>   
			 				<a class="fa fa-remove" title="Delete" href="javascript:void(0)" onClick="delProduct('<?php echo $product_id;?>','<?php echo $product_name;?>')"></a>
			 			</td>
			 		</tr>
			 	<?php } 
 				}
 			else { ?>
 				<tr><td colspan="7">No Products found</td></tr>
 				<?php } ?>
 		</table>
	</div>

In the last column, we are using an Action to update and delete a product. For delete, a JavaScript function delProduct() is used.

We will check in index.php, if the edit flag is set, we will display the Update form. If no flag is set, then we will show the Add form. See the code below:


<?php 
include "cfg/dbconnect.php";
$product_id = $p_id = $p_name = $price = $stock = $flag = ""; 
$product_found = false; 

if (isset($_REQUEST['flag']) && $_REQUEST['flag'] == 'edit'){		
		$flag = $_REQUEST['flag'];
		if (isset($_REQUEST['id'])) {
			$p_id = $_REQUEST['id'];
			$sql = "select * from product where product_id='$p_id'";
			$rs = mysqli_query($conn,$sql);
			if (mysqli_num_rows($rs) > 0) {
				$product_found = true;
				$row=mysqli_fetch_array($rs);
				$p_name = $row['product_name'];
				$price = $row['price'];
				$stock = $row['stock'];
			}
		}	
	}
?>
<?php if ($flag == "edit" && $product_found == true) { // Update Product Form ?>
<div class="col-md-4">
 	<h4>Update Product</h4>
 	<form id ="frm">
 	<input type="hidden" name="product_id" id="product_id" value="<?php echo $p_id;?>">
 	<div class="form-group col-md-12">
		 	<label>Product Name</label>
		 	<input type = "text" name="p_name" id = "p_name" class="form-control" maxlength="255" value="<?php echo $p_name;?>">
		 	<div class="error" id="product_err"></div>
	 </div>
	 <div class="form-group col-md-12">
		 	<label>Price</label>
		 	<input type = "number" name="price" id="price" class="form-control"  min=".01" max="9999.99" step ="any" value="<?php echo $price;?>">
		 	<div class="error" id="price_err"></div>
	 </div>
	 <div class="form-group col-md-12">
		 	<label>Stock</label>
		 	<input type = "number" name="stock" id="stock" class="form-control"  min="0"  value="<?php echo $stock;?>">
		 	<div class="error" id="stock_err"></div>
	 </div>
	 <div class="col-md-12 text-right">
	 		<a href ="index.php" class="btn btn-danger">Cancel</a> 
 			<input type ="button" class="btn btn-primary" onclick="updateProduct()" value="Save">
 	</div>
 </form>
</div>
<?php } else {  // Add Product Form ?>
	<div class="col-md-4">
	 	<h4>Add Product</h4>
	 	<form id ="frm">
	 	<div class="form-group col-md-12">
			 	<label>Product Name</label>
			 	<input type = "text" name="p_name" id = "p_name" class="form-control" maxlength="255">
			 	<div class="error" id="product_err"></div>
		 </div>
		 <div class="form-group col-md-12">
			 	<label>Price</label>
			 	<input type = "number" name="price" id="price" class="form-control"  min=".01" max="9999.99" step ="any">
			 	<div class="error" id="price_err"></div>
		 </div>
		 <div class="form-group col-md-12">
			 	<label>Stock</label>
			 	<input type = "number" name="stock" id="stock" class="form-control"  min="0">
		 		<div class="error" id="stock_err"></div>
		 </div>
		 <div class="col-md-12 text-right">
	 		<input type ="button" class="btn btn-primary" onclick="addProduct()" value="Add">
	 	</div>
	 </form>
	</div>
<?php } ?>

Note the save button in line 44. On the Onclick event of this button, we call a JavaScript function updateProduct(). This function will use Ajax to update the product details in the database. It is defined in product.js and we will explain it soon.

When the Edit Flag is not available, we display the Add Product form, see line 48. We call addProduct() function to add a product using Ajax. Below is the complete code of index.php.

index.php


<!DOCTYPE html>
<html lang="en">
<head>
  <title>Products</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" media="all"/>

  <link  rel="stylesheet" href="css/style.css">
</head>
<body>
  <div class="container">
    <h2>Add, Update and Delete Product using Ajax</h2>
    <div id="showMsg"></div>
	<?php 
	include "cfg/dbconnect.php";
	$product_id = $p_id = $p_name = $price = $stock = $flag = ""; 
	$product_found = false; 

	if (isset($_REQUEST['flag']) && $_REQUEST['flag'] == 'edit') {		
			$flag = $_REQUEST['flag'];
			if (isset($_REQUEST['id'])) {
				$p_id = $_REQUEST['id'];
				$sql = "select * from product where product_id='$p_id'";
				$rs = mysqli_query($conn,$sql);
				if (mysqli_num_rows($rs) > 0) {
					$product_found = true;
					$row=mysqli_fetch_array($rs);
					$p_name = $row['product_name'];
					$price = $row['price'];
					$stock = $row['stock'];
				}
			}	
		}
	?>	
	<div class="row">
		<div class="col-md-8">
			 <h4>Product List</h4>
			 <div class="table-responsive" id="products">
			 <table class="table table-bordered table-striped">
			 	<tr>
			 		<thead>
			 		<th>Serial No.</th><th>Product Id</th><th>Product Name</th><th>Price (<span class="fa fa-inr"></span>)</th><th>Stock</th><th>Action</th>
			 		</thead>
			 	</tr>	
			 	<?php 
			 	$select = "select * from product order by product_id";
			 	$products = mysqli_query($conn,$select); 
			 	$counter = 0;
			 	if (mysqli_num_rows($products) >0)
			 	 {
			 	foreach ($products as $product_row) { 
			 		$counter++;
			 		$product_id = $product_row['product_id'];
			 		$product_name= $product_row['product_name'];
			 		?>
			 		<tr>
			 			<td><?php echo $counter;?></td>
			 			<td><?php echo $product_row['product_id'];?></td>
			 			<td><?php echo $product_row['product_name'];?></td>
			 			<td><?php echo $product_row['price'];?></td>
			 			<td><?php echo $product_row['stock'];?></td>
			 			<td>
			 				<a class="fa fa-edit" title="Edit" href="index.php?id=<?php echo $product_id;?>&flag=edit"></a>   
			 				<a class="fa fa-remove" title="Delete" href="javascript:void(0)" onClick="delProduct('<?php echo $product_id;?>','<?php echo $product_name;?>')"></a>
			 			</td>
			 		</tr>
			 	<?php } 
			 }
			 	else { ?>
			 		<tr><td colspan="7">No Products found</td></tr>
			 		<?php } ?>
			 </table>
			</div>
			</div>
			<?php if ($flag == "edit" && $product_found == true) { // Update Product Form ?>
			<div class="col-md-4">
			 	<h4>Update Product</h4>
			 	<form id ="frm">
			 	<input type="hidden" name="product_id" id="product_id" value="<?php echo $p_id;?>">
			 	<div class="form-group col-md-12">
					 	<label>Product Name</label>
					 	<input type = "text" name="p_name" id = "p_name" class="form-control" maxlength="255" value="<?php echo $p_name;?>">
					 	<div class="error" id="product_err"></div>
				 </div>
				 <div class="form-group col-md-12">
					 	<label>Price</label>
					 	<input type = "number" name="price" id="price" class="form-control"  min=".01" max="9999.99" step ="any" value="<?php echo $price;?>">
					 	<div class="error" id="price_err"></div>
				 </div>
				 <div class="form-group col-md-12">
					 	<label>Stock</label>
					 	<input type = "number" name="stock" id="stock" class="form-control"  min="0"  value="<?php echo $stock;?>">
					 	<div class="error" id="stock_err"></div>
				 </div>
				 <div class="col-md-12 text-right">
				 		<a href ="index.php" class="btn btn-danger">Cancel</a> 
			 			<input type ="button" class="btn btn-primary" onclick="updateProduct()" value="Save">
			 	</div>
			 </form>
			</div>
		<?php } else {  // Add Product Form ?>
			<div class="col-md-4">
			 	<h4>Add Product</h4>
			 	<form id ="frm">
			 	<div class="form-group col-md-12">
					 	<label>Product Name</label>
					 	<input type = "text" name="p_name" id = "p_name" class="form-control" maxlength="255">
					 	<div class="error" id="product_err"></div>
				 </div>
				 <div class="form-group col-md-12">
					 	<label>Price</label>
					 	<input type = "number" name="price" id="price" class="form-control"  min=".01" max="9999.99" step ="any">
					 	<div class="error" id="price_err"></div>
				 </div>
				 <div class="form-group col-md-12">
					 	<label>Stock</label>
					 	<input type = "number" name="stock" id="stock" class="form-control"  min="0">
				 		<div class="error" id="stock_err"></div>
				 </div>
				 <div class="col-md-12 text-right">
			 		<input type ="button" class="btn btn-primary" onclick="addProduct()" value="Add">
			 	</div>
			 </form>
			</div>
		<?php } ?>
		</div>
	</div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <script src="js/product.js"></script>
</body>
</html>
	

Write JavaScript/jQuery for Ajax (product.js)

We have used three JavaScript functions - addProduct(), updateProduct() and delProduct(). For each of these functions, we have a corresponding PHP programs - add_product.php, update_product.php and delete_product.php. These PHP programs will be executed using an Ajax request.

Function addProduct()

This function is called when the user clicks on the Add button while adding a new product.


function addProduct()  {
	 var p_name = $('#p_name').val(); 
	 var price = $('#price').val();
	 var stock = $('#stock').val(); 
	 if (!validateData(p_name,price,stock))
	 	return false;
	
     $.ajax({  
           url:"add_product.php",  
           method:"POST",  
           data:{p_name:p_name, price:price,stock:stock}, 
           dataType:"text",  
           success:function(response) {  
           	$("#products").html(response);
           }  
      	}); 
	}

  1. url: add_product.php - this will take the form values and insert into product table. Also, it will refresh the list of products.
  2. type: "POST" - we are using post method.
  3. data: {p_name:p_name, price:price,stock:stock} - send the form values.
  4. dataType:"text" - response from Ajax will be in text format.

Now, let's see the code of add_product.php. It simply takes the input values and checks if product name already exists in database. If the product does not exist already, it will insert a row in the product table with the details of the product. It then selects all products from the product table and displays them in an html table.

add_product.php


<?php 
	include "cfg/dbconnect.php";
	$err_msg = $succ_msg = "";
	$p_name = trim($_POST['p_name']);  
	$price = $_POST['price'];
	$stock = $_POST['stock'];
	// check if same product name already exists
	$sql = "select * from product where product_name = '$p_name'";
	$result = mysqli_query($conn,$sql);
	if (mysqli_num_rows($result) > 0) 
		$err_msg = "Product already exists";

	else {
			$sql = "insert into product (product_name,price,stock) values('$p_name', '$price', '$stock')";
			$result = mysqli_query($conn,$sql);
			if ($result) 
				$succ_msg = "Product Added";
			else
				$err_msg = "Error: Could not add Product";
		}
	?>
	<table class="table table-bordered table-striped">
	 	<tr>
	 		<thead>
	 		<th>Serial No.</th><th>Product Id</th><th>Product Name</th><th>Price (<span class="fa fa-inr">)</th><th>Stock</th><th>Action</th>
	 		</thead>
	 	</tr>
	 	<?php 
	 	$select = "select * from product order by product_id";
	 	$products = mysqli_query($conn,$select); 
	 	$counter = 0;
	 	if (mysqli_num_rows($products) >0){
	 		foreach ($products as $product_row) { 
	 		$counter++;
	 		$product_id = $product_row['product_id'];
			$product_name= $product_row['product_name'];?>
	 		<tr>
	 			<td><?php echo $counter;?></td>
	 			<td><?php echo $product_row['product_id'];?></td>
	 			<td><?php echo $product_row['product_name'];?></td>
	 			<td><?php echo $product_row['price'];?></td>
	 			<td><?php echo $product_row['stock'];?></td>
	 			<td>
	 				<a class="fa fa-edit" title="Edit" href="index.php?id=<?php echo $product_id;?>&flag=edit"></a>   
			 		<a class="fa fa-remove" title="Delete" href="javascript:void(0)" onClick="delProduct('<?php echo $product_id;?>','<?php echo $product_name;?>')"></a>
	 			</td>
	 		</tr>
	 	<?php } 
	 	}
	 	else { ?>
	 		<tr><td colspan="7">No Products found</td></tr>
	 		<?php } ?>
	</table>
<script>
	// to display success or error message
	<?php if (!empty($succ_msg)) {?>
			$('#showMsg').html("<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button><?= $succ_msg;?></div>");
			clearValues();
			<?php }
		  if (!empty($err_msg)) {?>
			$('#showMsg').html("<div class='alert alert-danger alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button><?= $err_msg;?></span");
		<?php } ?>	
	
</script>

Function updateProduct()

This function is called when the user clicks on the Save button from the update form. It will validate the form and use Ajax to execute update_product.php. Let's see the code for this function.


function updateProduct()  {
	 var product_id = $('#product_id').val();  
	 var p_name = $('#p_name').val(); 
	 var price = $('#price').val();
	 var stock = $('#stock').val(); 
	 
	 if (!validateData(p_name,price,stock))
	 	return false;
	 if ($("#frm").data("changed")) {
          $.ajax({  
                   url:"update_product.php",  
                   method:"POST",  
                   data:{product_id:product_id, p_name:p_name, price:price,stock:stock}, 
                   dataType:"text",  
                   success:function(response) {  
                   	$("#products").html(response);
                   }  
              }); 
      	}
      	else {
      		alert("No changes to save");
      		return false;
      	}
	}

If form data is changed, we are executing Ajax in line 10.

  1. url: update_product.php - this takes the form values and updates the product table.
  2. type: "POST" - we are using post method.
  3. data: {product_id:product_id, p_name:p_name, price:price,stock:stock} - we are sending the form data. Note that product_id is the hidden field in the update form.
  4. dataType:"text" - Response from Ajax will be in text format.

Now, let's see the code of update_product.php. It gets the input values and checks if another product with the same name already exists in the database. If another product with the same name does not exist already, it will update the product table with the details of the product.

update_product.php


<?php 
	include "cfg/dbconnect.php";
	$err_msg = $succ_msg = "";
	$product_id = $_POST['product_id'];
	$p_name = trim($_POST['p_name']);  
	$price = $_POST['price'];
	$stock = $_POST['stock'];
	// check if same product name already exists
	$sql = "select * from product where product_name = '$p_name' and product_id <> '$product_id'";
	$result = mysqli_query($conn,$sql);
	if (mysqli_num_rows($result) >0) 
		$err_msg = "Product already exists";

	else {
		$sql = "update product set product_name = '$p_name',price = '$price',stock = '$stock' where product_id='$product_id'";
		$result = mysqli_query($conn,$sql);
		if ($result)
			$succ_msg = "Product Updated";
		else
			$err_msg = "Error: Could not update Product";
		}
?>
	<table class="table table-bordered table-striped">
	 	<tr>
	 		<thead>
	 		<th>Serial No.</th><th>Product Id</th><th>Product Name</th><th>Price (<span class="fa fa-inr">)</th><th>Stock</th><th>Action</th>
	 		</thead>
	 	</tr>
	 	<?php 
	 	$select = "select * from product order by product_id";
	 	$products = mysqli_query($conn,$select); 
	 	$counter = 0;
	 	if (mysqli_num_rows($products) >0)
	 	 {
	 		foreach ($products as $product_row) { 
	 		$counter++;
	 		$product_id = $product_row['product_id'];
			$product_name= $product_row['product_name'];?>
	 		<tr>
	 			<td><?php echo $counter;?></td>
	 			<td><?php echo $product_row['product_id'];?></td>
	 			<td><?php echo $product_row['product_name'];?></td>
	 			<td><?php echo $product_row['price'];?></td>
	 			<td><?php echo $product_row['stock'];?></td>
	 			<td>
	 				<a class="fa fa-edit" title="Edit" href="index.php?id=<?php echo $product_id;?>&flag=edit"></a>   
			 		<a class="fa fa-remove" title="Delete" href="javascript:void(0)" onClick="delProduct('<?php echo $product_id;?>','<?php echo $product_name;?>')"></a>
	 			</td>
	 		</tr>
	 	<?php } 
	 	}
	 	else { ?>
	 		<tr><td colspan="7">No Products found</td></tr>
	 		<?php } ?>
	</table>
<script>
	// to display success or error message
<?php if (!empty($succ_msg)) {?>
			$('#showMsg').html("<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button><?= $succ_msg;?></div>");
			clearValues();
			<?php }
		  if (!empty($err_msg)) {?>
			$('#showMsg').html("<div class='alert alert-danger alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button><?= $err_msg;?></span");
		<?php } ?>
	$("#frm").data("changed",false);	
	
</script>

Function delProduct(product_id, product_name)

This function is called when the user clicks on the delete link from the list of products. This will take the input parameters product_id and product_name.


function delProduct(product_id, product_name){
	if (confirm("Are you sure you want to delete product - "+product_name+"?")){
		$.ajax({  
                   url:"delete_product.php",  
                   method:"POST",  
                   data:{product_id:product_id}, 
                   dataType:"text",  
                   success:function(response) {  
                   	$("#products").html(response);
                   }  
              }); 
	}
} 

Now, let's see the code of delete_product.php. It works the same way as adding and updating a product. It takes the input parameter product_id and deletes the product from the product table.

delete_product.php


<?php 
	include "cfg/dbconnect.php";
	$product_id = $_POST['product_id'];
	$sql = "delete from product where product_id='$product_id'";
	$result = mysqli_query($conn,$sql);
	if ($result)
			$succ_msg = "Product Deleted";
		else
			$err_msg = "Error: Could not delete Product";
	?>
	<table class="table table-bordered table-striped">
	 	<tr>
	 		<thead>
	 		<th>Serial No.</th><th>Product Id</th><th>Product Name</th><th>Price (<span class="fa fa-inr">)</th><th>Stock</th><th>Action</th>
	 		</thead>
	 	</tr>
	 	<?php 
	 	$select = "select * from product order by product_id";
	 	$products = mysqli_query($conn,$select); 
	 	$counter = 0;
	 	if (mysqli_num_rows($products) >0)
	 	 {
	 		foreach ($products as $product_row) { 
	 		$counter++;
	 		$product_id = $product_row['product_id'];
			$product_name= $product_row['product_name'];?>
	 		<tr>
	 			<td><?php echo $counter;?></td>
	 			<td><?php echo $product_row['product_id'];?></td>
	 			<td><?php echo $product_row['product_name'];?></td>
	 			<td><?php echo $product_row['price'];?></td>
	 			<td><?php echo $product_row['stock'];?></td>
	 			<td>
	 				<a class="fa fa-edit" title="Edit" href="index.php?id=<?php echo $product_id;?>&flag=edit"></a>   
			 		<a class="fa fa-remove" title="Delete" href="javascript:void(0)" onClick="delProduct('<?php echo $product_id;?>','<?php echo $product_name;?>')"></a>
	 			</td>
	 		</tr>
	 	<?php } 
	 	}
	 	else { ?>
	 		<tr><td colspan="7">No Products found</td></tr>
	 		<?php } ?>
	</table>
<script>
<?php if (!empty($succ_msg)) {?>
			$('#showMsg').html("<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button><?= $succ_msg;?></div>");
			clearValues();
			<?php }
		  if (!empty($err_msg)) {?>
			$('#showMsg').html("<div class='alert alert-danger alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button><?= $err_msg;?></span");
		<?php } ?>

</script>

Function validateData()

validateData() function is called by addProduct() and updateProduct() functions in product.js. This function is used to validate the form.


function validateData(p_name,p_price,p_stock){
	 if (p_name.trim() =="")  {
	  $("#product_err").text("Product Name must have a value");
	  return false;
	  }
	  if (p_price.trim() == "") p_price = 0;
 	  if(p_price <= 0)
		{
	  	$("#price_err").html("Enter a positive value for price");
	  	$("#price").focus();
	  	return false;
	  	}
	  if (p_stock.trim() == "") {
	  	$("#stock_err").html("Stock should be zero or positive");
	  	$("#stock").focus();
	  	return false;
	  }
	  if (p_stock <0) {
	  	$("#stock_err").html("Stock should be zero or positive");
	  	$("#stock").focus();
	  	return false;
	  }
	return true;
}

Add CSS (style.css)

Let us add below styles. We have already added style.css in index.php.

style.css


h2{
  margin-top: 20px;
}
h4{
  margin-top: 30px;
}
h2,h4{
	text-align: center;
}
#showMsg{
  width:auto;
  height: 30px;
  text-align: center;
}
label{
    font-weight: bold;
  }
table{
  width:100%;
}
table,th,td {
  margin:auto;
  border-collapse: collapse;
  border:1px solid #c4b2b2;
  }
thead {
  background-color: #265159;
  color:#fff;

}
thead,tbody {
  text-align: center;
}
a{
  text-decoration: none;
  color: #000;
}
.error{
  color: red;
}

insert, update and delete in php with ajax jqueryTest the Application

Make sure in your XAMPP control panel Apache and MySQL services are running. Run localhost/product in the browser. You will see the home page displayed below:

insert, update, delete and view data without refresh using php, mysql and ajax

Add a new product, update an existing product and delete a product. Verify the data in the database table.

download source code for crud form without refreshing in webpage using the jquery and ajaxDownload Source Code

Download the source code by clicking on the download button below:

crud operation in php and ajaxConclusion

In this example, we have shown how you can develop a CRUD application (add/update/delete) using PHP and Ajax so that you do not need to refresh the entire web page. There could be cases where you do not want to submit a form, but you want to refresh a part of the web page. In such cases, Ajax can help us.

Post a Comment

Save my Name and Email id for future comments