Insert, Update and Delete Operations via jQuery & Ajax in PHP + MySQL (Wall Script)

In the previous post, we went through the CRUD Operation i.e. Insert, Read, Update and Delete using PHP and MySQL and had built a small wall script. In this post, we will be doing a quite same thing but totally in a different way. If you remember in the last post, our data were getting refreshed each time whenever we performed any activity whether it may be a new post, editing data or deleting it. That means, for any small changes we were displaying the whole data, again and again, resulting in the loss of time, internet data and web page performance. To get rid of these problems, a new web technology for client side called AJAX was developed. With the help of AJAX, our web apps can send and receive the data to the servers in the background without interfering the already existing web page. That means it will interchange the data asynchronously. For this purpose, we will use a lightweight JavaScript framework known as jQuery which supports Ajax.

Insert-Update-Delete-JQuery-Ajax-PHP



we are repeating some steps of previous post


Script Files

  • jquery-3.1.1.min.js
  • dbConfig.php
  • Delete.php
  • index.php
  • Insert.php
  • Update.php


Creating Database and Table

First I have created a Database with name "inspire2code" and then i have created a "MyData" table in that database

CREATE TABLE `inspire2code`.`wall`
  ( `ID` INT(100) NOT NULL AUTO_INCREMENT ,
 `Name` VARCHAR(200) NOT NULL ,
 `Content` VARCHAR(200) NOT NULL ,
 `ProfileImg` VARCHAR(200) NOT NULL ,
  PRIMARY KEY (`ID`)) ENGINE = MyISAM;

mysql_table


index.php : We are Performing Insert & View Operation on the same page

Post Insertion Design

<div class="Main">
<h1 style="font-size:28px;" align="center">Wall feed implementation via jQuery, Ajax & PHP </h1>
<div class="InnerMain">
<div class="ProfileDiv" ><img src="profile.jpg" class="Profile" /></div>
<div class="ContentDiv">

<textarea class="TextArea" name="Content" id="Content"></textarea>
<input type="submit" class="btn btn-outline-info submit"  style="margin-top:10px;" name="Post" value="POST" />
<span id="loader"><img src="loader.gif" style="vertical-align:middle;" /></span>
</div>

</div>
</div>

insert
Creating Database Connection in MySQL

We are creating a separate file for connection and then we will import in index.php using

<?php require('DbConfig.php'); ?>

DbConfig.php

 <?php

//defining name
define('SERVER', 'localhost');
define('USER', 'root');
define('PASSWORD', '');
define('DB', 'inspire2code');

//Establishing connection to mysql
$link = mysqli_connect(SERVER, USER, PASSWORD, DB)
        or die("Erro-> ".mysqli_connect_error());


?>   
jQuery codes for sending our data from index.php to Insert.php page
index.php

Line no. 2 : We are importing jQuery library file jquery-3.1.1.min.js to use jQuery & Ajax function on the page
You can download this from jQuery official site http://jquery.com/download/

We can also import this library file from jQuery website via CDN (Content Delivery Network)

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
some other providers are :


 <script src="jQuery/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function(e) {

$('.submit').on('click',function(e) {
	var Content = $('#Content').val();
	var Data = {Content:Content};
         if(Content!='') {
	$.ajax({
		type:"POST",
		url:"Insert.php",
		data:Data,
		beforeSend: function(){$('#loader').show();},
		success: function(data) {
		if(data) {
			$('#content').prepend(data);
			$('#loader').hide();
			$('#Content').val('');
			     }
			                       }
		   });
	               }
	});

    //Update jQuery codes

});
</script> 

With above jQuery code, data will be carried out to Insert.php

Insert.php

if you observe in the above jQuery code on Line no. 8 We have encapsulated the data in a data string variable with var Data = {Content(PHP):Content(JavaScript)}; where left "Content" is a variable which is carrying data from right side javascript variable "Content" to Insert.php page
Line no. 3 : Here, we are checking if Content has any value/data using if(isset($_POST['Content'])) { };


<?php
if(isset($_POST['Content'])) {

require('DbConfig.php');

$Content=trim($_POST['Content']);
$Content = mysqli_escape_string($link,$Content);
$Name="Rohit Sharma";
$ProfileImg = "Profile.jpg";
if(!empty($Content)) {
$Query= "INSERT INTO `wall` SET
         Name       = '$Name',
		 Content    = '$Content',
		 ProfileImg = '$ProfileImg'";


$Execute = mysqli_query($link,$Query);

if($Execute==true)
{
$Query  = "SELECT * FROM `wall` ORDER BY ID DESC LIMIT 1";
$Execute = mysqli_query($link,$Query);
$Result = mysqli_fetch_assoc($Execute);

//Show Last inserted Post

}
                     }

                                     }
	?>

Codes to be written in above Line no. 26

This will fetch the last inserted record to display on the main page index.php
//Show Last inserted Post

<div class="subdiv" id="subdiv<?php echo $Result['ID']; ?>">
<div class="InnerMain">
<div class="ProfileDiv"><img src="<?php echo $Result['ProfileImg']; ?>" class="ProfileWall"></div>
<div class="ContentDiv border">
<div class="container" id="text<?php echo $Result['ID']; ?>"><?php echo nl2br($Result['Content']); ?></div>
<div style="margin-top:27px;">
<a class="update" id="<?php echo $Result['ID']; ?>" href="#">Edit</a>
<a style="color:red;" class="delete" id="<?php echo $Result['ID']; ?>" href="#">Delete</a></div>
</div>
</div>
</div>

insert

Designing Update Box


insert

   <div class="Main passive">
<h1 style="font-size:28px;" align="center">Update this post</h1>
<div class="InnerMain">
<div class="ProfileDiv" ><img src="profile.jpg" class="Profile" /></div>
<div class="ContentDiv">

<textarea class="TextArea" name="Content" id="Modify"></textarea>
<input type="submit" class="btn btn-outline-info updates" id="" style="margin-top:10px;" name="Update" value="UPDATE" />
<span id="loaders"><img src="loader.gif" style="vertical-align:middle;" /></span>
</div>

</div>
</div>
   
jQuery code for moving Content to UpdateBox Textarea
index.php
insert


 $('#content').on('click','.update', function(e){
		var id = $(this).attr('id');
		$('#start').hide();
		$('.passive').show();
		var data = $('#text'+id).html();
	    $('#Modify').val(data);
		$('.updates').attr('id',id);
		});

 

jQuery codes for sending our data from index.php to Update.php page
index.php


 $('.updates').on('click', function(e){
		var text = $('#Modify').val();
		var id = $('.updates').attr('id');
		var Data = {text:text,id:id};
               if(text!='' && id!='') {
		$.ajax({
			type:"POST",
			url:"Update.php",
			data:Data,
			beforeSend: function(){$('#loaders').show();},
			success: function(data){
				if(data){
					$('.passive').hide();
					$('#start').show();
					$('#loaders').hide();
					$('#text'+id).html(text);
					$('#text'+id).addClass('box');
					setTimeout(function(){
					$('#text'+id).removeClass('box');
					},1000);
					}

				}
			});
                                       }
		});

 

Update.php

  <?php

if(isset($_POST['text'])) {
	require('DbConfig.php');

$Content=trim($_POST['text']);

$ID = trim($_POST['id']);
$Content= mysqli_escape_string($link,$Content);
if(!empty($ID) && !empty($Content)) {
$Query= "UPDATE `wall` SET
         Content    = '$Content'
		 WHERE ID='$ID'";


$Execute = mysqli_query($link,$Query);

if($Execute==true)
{

	echo "Done";

	}


                                  }
}

?>
  
insert
jQuery codes for sending our data from index.php to Delete.php page
index.php



	$('#content').on('click','.delete' ,function(e){
		var id = $(this).attr('id');
		var Data = {id:id};
                 if(id!='') {
		$.ajax({
			type:"POST",
			url:"Delete.php",
			data:Data,
			success: function(){$('#subdiv'+id).fadeOut(1000);}
			});
                            }
		});
 

Delete.php

 <?php
if(isset($_POST['id'])) {
	require('DbConfig.php');

$ID = trim($_POST['id']);
$ID = mysqli_escape_string($link,$ID);

$Query= "DELETE FROM `wall` WHERE ID='$ID'";


$Execute = mysqli_query($link,$Query);

			           }


?>
  
insert

People Reaction : 3

Sandeep
15th Oct 16 AT 11:50 AM Sandeep
Hey Rohit, This is really good one but i have found some bugs in your code. Take a look on demo part, we can update the post even if the text area is empty.
Rohit Sharma
15th Oct 16 AT 11:50 AM Rohit Sharma
Bugs Fixed. Thank you Sandeep for observing this bugs.
Kailas
1st Jan 17 AT 8:55 AM Kailas
Thanks. Great topic
Rohit Sharma
Name : Email : Website :
Rohit Sharma

Hi There! My name is Rohit and I am working in the one of MNC as Web Apps developer. I have been in this tech industry for last 3.6 years. This blog is just a part of my career journey.
Ready to make new mistakes without repeating the previous ones.

"All life is an experiment. The more experiments you make the better"


© 2020 WriteSomeCode. All Right Reserved. A Rohit Sharma Blog. Creative Commons License licensed under a Creative Commons Attribution 4.0 International License