CRUD Operations Using Ajax - Part 2

Introduction
 
Here's part-2 of the series and it shows CRUD operations using Ajax or without loading the page and binding the data in HTML Table using Ajax with edit and delete operations.
 
Description 
 
Before moving to the article I will suggest you to visit my first article to save data in the database and bind in HTML table using Ajax. Here's the link:
After the first article we completed till the following:

Eployee detail 

Admin Employee table
 
Step 1: (For Edit Option).

The Edit button has the following code:
  1. <input type="button" class="btn btn-primary editButton" data-id="<%=TableData.Rows[data]["EmpId"] %>" data-toggle="modal" data-target="#myModal" name="submitButton" id="btnEdit" value="Edit" /></td>  
data-id  is bind with EmpId so that on clicking that particular row button,  respective data from the database of EmpID will be the  Popup.

Here I have used PopUp edit of BootStrap for displaying it in a better way.

HTML Code for PopUp Edit is as in the following code snippet:
  1. <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" id="myModal">  
  2.         <div class="modal-dialog" role="document">  
  3.             <div class="modal-content">  
  4.                 <div class="modal-header">  
  5.                     <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>  
  6.                     <h2 class="modal-title" id="myModalLabel">Modal title</h2>  
  7.                 </div>  
  8.                 <div class="modal-body">  
  9.                     <div class="panel-body">  
  10.                         <div class="form-group col-lg-4">  
  11.                             <label>First Name</label>  
  12.                             <input type="text" name="FirstName" id="FirstName1" class="form-control" placeholder="Ajay" required="" />  
  13.                         </div>  
  14.   
  15.                         <div class="form-group col-lg-4">  
  16.                             <label>Middle Name</label>  
  17.                             <input type="text" name="MiddleName" id="MiddleName1" class="form-control" placeholder="Kumar" required="" />  
  18.                         </div>  
  19.                         <div class="form-group col-lg-4 ">  
  20.                             <label>Surname</label>  
  21.                             <input type="text" name="Surname" id="Surname1" class="form-control" placeholder="Gupta" required="" />  
  22.                         </div>  
  23.   
  24.                         <div class="form-group col-lg-4">  
  25.                             <label>Gender</label>  
  26.                             <label class="radio-inline">  
  27.                                 <input type="radio" checked="" value="Male" id="Male1" name="Gender" />  
  28.                                 Male  
  29.   
  30.                             </label>  
  31.                             <label class="radio-inline">  
  32.                                 <input type="radio" value="Female" id="Female1" name="Gender" />  
  33.                                 Female.  
  34.                             </label>  
  35.                         </div>  
  36.                         <div class="clearfix"></div>  
  37.                         <div class="form-group col-lg-6">  
  38.                             <label>Email ID</label>  
  39.                             <input type="email" readonly="readonly" name="EmailId" id="EmailId1" class="form-control" placeholder="abc@someone.com" required="" />  
  40.                         </div>  
  41.                         <div class="form-group col-lg-6">  
  42.                             <label>Date of Birth </label>  
  43.                             <input type="date" name="Dob" id="Dob1" min="1920-01-02" class="form-control datepicker" required="" />  
  44.                         </div>  
  45.                         <div class="form-group col-lg-6">  
  46.                             <label>MaritalStatus</label>  
  47.                             <select name="MaritalStatus" id="MaritalStatus1" class="form-control" required="">  
  48.                                 <option value="" disabled="disabled">-- Select -- </option>  
  49.                                 <option value="Single">Single</option>  
  50.                                 <option value="Married">Married</option>  
  51.                             </select>  
  52.                         </div>  
  53.                         <div class="form-group col-lg-6">  
  54.                             <label>Hobbies</label>  
  55.                             <input type="text" name="Hobbies" id="Hobbies1" class="form-control" placeholder="Football, Cricket etc." />  
  56.                         </div>  
  57.                         <div class="form-group col-lg-6">  
  58.                             <label>Home Telephone</label>  
  59.                             <input type="text" name="TelephoneNo" id="TelephoneNo1" class="form-control" placeholder="1234567890" />  
  60.                         </div>  
  61.                         <div class="form-group col-lg-6">  
  62.                             <label>Mobile</label>  
  63.                             <input type="tel" name="MobileNo" id="MobileNo1" class="form-control" required="" placeholder="0987654321" />  
  64.                         </div>  
  65.                         <div class="form-group col-lg-12">  
  66.                             <label>Residential Address</label>  
  67.                             <textarea rows="2" name="ResidentialAddress" id="ResidentialAddress1" class="form-control" required=""></textarea>  
  68.                         </div>  
  69.                         <div class="form-group col-lg-6 ">  
  70.                             <label>Pin Code</label>  
  71.                             <input type="text" name="PinCode" id="PinCode1" class="form-control" placeholder="999999" />  
  72.                         </div>  
  73.                         <div class="form-group col-lg-6">  
  74.                             <label>State</label>  
  75.                             <select name="State" id="State1" class="form-control" required="">  
  76.                                 <option value="" disabled="disabled">-- Select -- </option>  
  77.                                 <option value="Maharashtra">Maharastra</option>  
  78.                                 <option value="Bihar">Bihar</option>  
  79.                                 <option value="Delhi">UP</option>  
  80.                                 <option value="Odisha">Odisha</option>  
  81.                                 <option value="Odisha">AP</option>  
  82.                             </select>  
  83.                         </div>  
  84.                         <div class="form-group col-lg-6">  
  85.                             <label>Nationality</label>  
  86.                             <input type="text" name="title" id="Nationality1" class="form-control" placeholder="Indian" required="" />  
  87.                         </div>  
  88.                         <div class="form-group col-lg-6">  
  89.                             <label>Date of Joining</label>  
  90.                             <input type="date" name="Doj" id="Doj1" class="form-control datepicker" required="" />  
  91.                         </div>  
  92.                     </div>  
  93.                 </div>  
  94.                 <div class="modal-footer">  
  95.                     <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>  
  96.                     <button type="button" id="btnUpdate" class="btn btn-primary" edit-id="" data-dismiss="modal">Save changes</button>  
  97.                 </div>  
  98.             </div>  
  99.         </div>  
  100.     </div>  
  101. </div>
My scripting code for edit is as the following:
  1. $(document).on("click"".editButton", function() {  
  2.     $('#myModal').focus();  
  3.     var id = $(this).attr("data-id");  
  4.     console.log(id);  
  5.     $("#btnUpdate").attr("edit-id", id); // Here I am Passing the ID of that edit id to update that specific data  
  6.     //alert(id);  //getting the row id     
  7.     $.ajax({  
  8.         type: "Post",  
  9.         contentType: "application/json; charset=utf-8",  
  10.         url: "Default.aspx/EditData"// Default.aspx is the Page and EditData() is my WebMethod  
  11.         data: '{eid: ' + id + '}'// Showing the Details of Record of Specific ID  
  12.         dataType: "json",  
  13.         success: function(data) {  
  14.             var empDetails = $.parseJSON(data.d);  
  15.             $.each(empDetails, function(index, value) {  
  16.                 //console.log(v.Fname);    
  17.                 $("#FirstName1").val(value.Fname);  
  18.                 $("#MiddleName1").val(value.Mname);  
  19.                 $("#Surname1").val(value.Lname);  
  20.                 $("#EmailId1").val(value.EMail);  
  21.                 $("#Dob1").val(value.DOB);  
  22.                 $("#MaritalStatus1").val(value.MaritalStatus);  
  23.                 $("#Hobbies1").val(value.Hobbies);  
  24.                 $("#TelephoneNo1").val(value.Telephone);  
  25.                 $("#MobileNo1").val(value.Mobile);  
  26.                 $("#ResidentialAddress1").val(value.Address);  
  27.                 $("#PinCode1").val(value.PinCode);  
  28.                 $("#State1").val(value.State);  
  29.                 $("#Nationality1").val(value.Nationality);  
  30.                 $("#Doj1").val(value.DOJ);  
  31.             });  
  32.         },  
  33.         error: function() {  
  34.             alert("Error while retrieving data of :" + id);  
  35.         }  
  36.     });  
  37. });  
WebMethod for Edit is the following:
  1. [WebMethod]    
  2. public static string EditData(int eid) //Show the edit clicked data in the popup window    
  3. {    
  4.     string jsondata;    
  5.     //var details = new List<Employee>();    
  6.     using (var con = new SqlConnection(Constr))    
  7.     {    
  8.         var query = "select * from TblUser where EmpId='" + eid + "' order by EmpId desc";    
  9.         using (var cmd = new SqlCommand(query, con))    
  10.         {    
  11.             using (var sda = new SqlDataAdapter())    
  12.             {    
  13.                 cmd.Connection = con;    
  14.                 sda.SelectCommand = cmd;    
  15.                 TableData.Clear();    
  16.                 sda.Fill(TableData);    
  17.                 jsondata = JsonConvert.SerializeObject(TableData);    
  18.             }    
  19.         }    
  20.     }    
  21.     return jsondata;  
  22. }    
After that it will look like the following:
 
 

Step 2:
(For Update Records).

After updating records we can go for saving the changes. The code for updating the script is shown below:
  1. $("#btnUpdate").click(function() {  
  2.     var id = $(this).attr("edit-id");  
  3.     var user = {};  
  4.     user.FName = $("#FirstName1").val();  
  5.     user.LName = $("#Surname1").val();  
  6.     user.MName = $("#MiddleName1").val();  
  7.     user.Gender = $("#Male1").val();  
  8.     user.Email = $("#EmailId1").val();  
  9.     user.Dob = $("#Dob1").val();  
  10.     user.MaritalStatus = $("#MaritalStatus1").val();  
  11.     user.Hobbies = $("#Hobbies1").val();  
  12.     user.HomeMobile = $("#TelephoneNo1").val();  
  13.     user.OfficeMobile = $("#MobileNo1").val();  
  14.     user.Address = $("#ResidentialAddress1").val();  
  15.     user.Pincode = $("#PinCode1").val();  
  16.     user.State = $("#State1").val();  
  17.     user.Nationality = $("#Nationality1").val();  
  18.     user.Doj = $("#Doj1").val();  
  19.     user.ModifiedDateTime = new Date();  
  20.     $.ajax({  
  21.         type: "Post",  
  22.         contentType: "application/json; charset=utf-8",  
  23.         url: "Default.aspx/UpdateData",  
  24.         data: '{objEmployee: ' + JSON.stringify(user) + ', eid : ' + id + '}'// Id came from edit button  
  25.         dataType: "json",  
  26.         success: function(data) {  
  27.             if (confirm("Are you sure you want to change !") == true) {  
  28.                 alert("Data Updated successfully");  
  29.             } else {  
  30.                 alert("You have canceled the changes");  
  31.             }  
  32.             getDetails(); // To Show the updated data after updation   
  33.         },  
  34.         error: function(data) {  
  35.             alert("Error while Updating data of :" + id);  
  36.         }  
  37.     });  
  38. });  
For Delete We have to change the Ajax getDetails() Method as follows
  1. function getDetails() {  
  2.                $.ajax({  
  3.                    type: "POST",  
  4.                    contentType: "application/json; charset=utf-8",  
  5.                    url: "Default.aspx/GetData",  
  6.                    data: {},  
  7.                    dataType: "json",  
  8.                    success: function(data) {  
  9.                        $('#dataTables-example tbody').remove();  
  10.                        //console.log(data.d);  
  11.                        for (var i = 0; i < data.d.length; i++) {  
  12.                            $("#dataTables-example").append(  
  13.                                "<tr><td>" + data.d[i].FName + "</td><td>" + data.d[i].Email + "</td>" +  
  14.                                "<td>" + data.d[i].HomeMobile + "</td>" + "<td>" + data.d[i].OfficeMobile + "</td>" +  
  15.                                "<td>" + data.d[i].Doj + "</td>" + "<td>" + data.d[i].Dob + "</td>" +  
  16.                                "<td>" + "<input type='button' class='btn btn-primary editButton' data-id='" + data.d[i].EmpId + "' data-toggle='modal' data-target='#myModal' name='submitButton' id='btnEdit' value='Edit' />" + "</td>" +  
  17.                                "<td><input type='button' class='btn btn-primary deleteButton' data-id='" + data.d[i].EmpId + "' name='submitButton' id='btnDelete' value='Delete'/> </td></tr>");  
  18.                        }  
  19.                    },  
  20.                    error: function() {  
  21.                        alert("Error while Showing update data");  
  22.                    }  
  23.                });  
  24.            }  
 
See my Ajax data. Here I am passing all the details of Employee object in JSON format along with the Id to update specific record.

On success, I am calling getDetails() to show updated data in the HTML table.

My WebMethod for updating the records is the following:
  1. [WebMethod]    
  2. public static void UpdateData(Employee objEmployee, int eid) //Update data in database      
  3. {    
  4.     using (var con = new SqlConnection(Constr))    
  5.     {    
  6.         var query = "update TblUser set Hobbies='" + objEmployee.Hobbies + "',Fname='" + objEmployee.FName +    
  7.                     "',Lname='" + objEmployee.LName + "',Mname='" + objEmployee.MName + "'," +    
  8.                     "Dob='" + objEmployee.Dob + "',MaritalStatus='" + objEmployee.MaritalStatus + "',Address='" +    
  9.                     objEmployee.Address + "', Telephone='" + objEmployee.OfficeMobile + "'," +    
  10.                     "Mobile='" + objEmployee.HomeMobile + "',Pincode='" + objEmployee.Pincode + "',State='" +    
  11.                     objEmployee.State + "',Nationality='" + objEmployee.Nationality + "', " +    
  12.                     "Doj='" + objEmployee.Doj + "'where EmpId='" + eid + "'";    
  13.         con.Open();    
  14.         var cmd = new SqlCommand(query, con);    
  15.         cmd.ExecuteNonQuery();    
  16.         con.Close();    
  17.     }    
  18. }    
Step 3: (For Delete Records).

Here's the delete button html:
  1. <input type="button" class="btn btn-primary deleteButton" data-id="<%=TableData.Rows[data]["EmpId"] %>" name="submitButton" id="btnDelete" value="Delete" />  
data-id -From this I am taking EmployeeID to delete specific records. Also I have added a class deleteButton to identify all the delete clicks with that class:  
  1. $(document).on("click"".deleteButton", function() {  
  2.     var id = $(this).attr("data-id");  
  3.     $.ajax({  
  4.         type: "Post",  
  5.         contentType: "application/json; charset=utf-8",  
  6.         url: "Default.aspx/Remove"// Remove is the Webmethod in Default.aspx Page  
  7.         data: '{eid: ' + id + '}',  
  8.         dataType: "json",  
  9.         success: function() {  
  10.             if (confirm("Are you sure you want to delete !") == true) {  
  11.                 alert("Data Deleted successfully");  
  12.             } else {  
  13.                 alert("You have canceled the changes");  
  14.             }  
  15.             //alert("Data Updated successfully");    
  16.             getDetails();  
  17.         },  
  18.         error: function(data) {  
  19.             alert("Error while Updating data of :" + id);  
  20.         }  
  21.     });  
  22. }
My WebMethod for Delete record.
  1. [WebMethod]    
  2. public static void Remove(int eid)    
  3. {    
  4.     using (var con = new SqlConnection(Constr))    
  5.     {    
  6.         var query = "delete from dbo.TblUser where EmpId='" + eid + "'";    
  7.         con.Open();    
  8.         var cmd = new SqlCommand(query, con);    
  9.         cmd.ExecuteNonQuery();    
  10.         con.Close();    
  11.     }    
  12. }  
After this we can delete particular record and also see that after Ajax I am calling getDetails(); to show latest data.

Also for inserting multiple rows in the database from HTML table using Ajax and jQuery please visit here.

You can download the entire application attached above that includes both Part-I and Part-2.

Hope that helps and thanks for reading.