PHP AJAX CRUD Tutorial: Create, Read, Update, Delete Without Page Reload

Building a CRUD application in PHP and AJAX is one of the most practical skills for a web developer. In this tutorial, you will learn how to use the Create, Read, Update, and Delete operations in PHP using jQuery AJAX without page reload. This beginner-friendly guide will help you understand how AJAX works behind the scenes to make web applications faster, dynamic and more interactive.

We will develop an application that allows users to view a list of products, add new products, update existing products, and delete products using PHP and MySQL with jQuery Ajax. This will be a fully functional PHP AJAX CRUD project for you.

You can use it for Admin to maintain products or items in the system.

make CRUD operations with AJAXProject Folders

PHP AJAX CRUD tutorial

We will use a folder named 'product' under 'xampp/htdocs'. This will be our project root.

You can see I have created separate PHP file dbconnect.php to connect to the MySQL database. So that I can include it in other programs.

index.php is the main program that displays a list of products and gives options to add, update and delete products. For insert, update and delete I have separate PHP programs which are used with Ajax request.

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 to store products

PHP CRUD Operations without Page Refresh ajax jQuery

Columns are:

  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;

Database Connection (dbconnect.php)

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());

You can also read the tutorial 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 html table to show the list of existing products (Read). In the same screen, we also have an "Add" (Create) form and an "Update" (Update) form . 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 options. For updating the product, call the same program (index.php) with the product id and an edit flag as parameters. Call a JavaScript function to delete the product using Ajax.
  3. When no flag is set, show the "Add" product form

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

If the edit flag is set, we will display the "Update" form. If no flag is set, we will display 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>
	

jQuery Ajax code (product.js)

We have used three JavaScript functions - addProduct(), updateProduct() and delProduct(). In each of these functions, we will use add_product.php, update_product.php and delete_product.php with Ajax requests.

Function addProduct()

This function is called when the user clicks on the "Add" button to add 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 use the form values and insert into product table. Also, it will refresh the list of products.
  2. type: "POST" - post method is used.
  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, it will insert a row in the "product" 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>
	
	<?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. Note that product_id is the hidden field in the update form.

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, it updates 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 add and update. 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;
}

You can test this CRUD application by creating a new product and then updating and deleting it. Verify the data in the database table after each operation.

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

CRUD applications in PHP and AJAX without page reload are faster, smoother, and more user-friendly. Using jQuery AJAX to handle insert, update, delete, and fetch operations allows real-time interaction with the MySQL database. I hope this PHP AJAX CRUD example will be useful to you for developing advanced dynamic web applications.

Please write your comments/questions in Comments section below. Your questions, doubts and suggestions are always welcome.

2 Thoughts on "PHP AJAX CRUD Tutorial: Create, Read, Update, Delete Without Page Reload"

Post a Comment

Save my Name and Email id for future comments