Auto Save Using AJAX

Introduction
 
This article explains how to automatically save a value into a SQL database using an ASP.Net WebMethod and jQuery Ajax.
 
jQuery
 
The following code shows that SaveDraft.aspx is the aspx page and AutoSave is the method. We pass the client-side value to the server-side using Ajax and WebMethod.
  1. $(document).ready(function () {  
  2.       // Configure to save every 5 seconds  
  3.       window.setInterval(saveDraft, 5000);//calling saveDraft function for every 5 seconds  
  4.   
  5. });  
  6.   
  7. // ajax method  
  8. function saveDraft() {  
  9.   
  10.    $.ajax({  
  11.        type: "POST",  
  12.        contentType: "application/json; charset=utf-8",  
  13.        url: "SaveDraft.aspx/AutoSave",  
  14.        data: "{'firstname':'" + document.getElementById('Firstname').value + "','middlename':'" + document.getElementById('Middlename').value + "','lastname':'" + document.getElementById('Lastname').value + "'}",  
  15.   
  16.       success: function (response) {  
  17.   
  18.       }  
  19.   
  20.   });  
  21. }  
In the following code the saveDraft function fires every 5 seconds. The value will be saved in the database every 5 seconds without post-backs. Based on our requirements we can change the time interval. 
  1. $(document).ready(function () {  
  2.      // Configure to save every 5 seconds  
  3.      window.setInterval(saveDraft, 5000);//calling saveDraft function for every 5 seconds  
  4.   
  5. });  
Database structure
 
Create a table in a database for storing the personal information.The following SQL code contains an existing person's details. So we can change those values at runtime without a post-back and button-click. 
  1. USE [TestDB]  
  2. GO  
  3. /****** Object:  Table [dbo].[Autosave]    Script Date: 08/07/2015 18:19:54 ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE TABLE [dbo].[Autosave](  
  9.     [Id] [intNULL,  
  10.     [firstname] [nvarchar](50) NULL,  
  11.     [middlename] [nvarchar](50) NULL,  
  12.     [lastname] [nvarchar](50) NULL  
  13. ON [PRIMARY]  
  14. GO  
  15. INSERT [dbo].[Autosave] ([Id], [firstname], [middlename], [lastname]) VALUES (1, N'Rajeesh', N'', N'Menoth')  
C#
 
The WebMethod will catch the client-side value in the server side. In the given example I am passing the id directly into the update query. You can modify the code for your requirements. 
  1. [WebMethod]  
  2.     public static string AutoSave(string firstname, string middlename, string lastname)  
  3.     {  
  4.         int id = 1;  
  5.         string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;  
  6.         SqlConnection con = new SqlConnection(ConnectionString);  
  7.         {  
  8.             string str = "Update Autosave set firstname='" + firstname + "',middlename= '" + middlename + "',lastname= '" + lastname + "' where Id=" + id + "";  
  9.             SqlCommand cmd = new SqlCommand(str, con);  
  10.             {  
  11.                 con.Open();  
  12.                 cmd.ExecuteNonQuery();  
  13.                 return "True";  
  14.             }  
  15.         }  
  16.   
  17.     }   
Important Section
 
1. Namespace 
 
The given namespace contains the WebMethod,database connection libraries.
  1. using System.Web.Services; 
  2. using System.Data.SqlClient;  
2. Reference
 
Add the following jQuery reference.
  1. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>  
  2. script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>  
 
                                                            Figure 1
Output
 
 
                                                            Figure 2
 
Reference
Summary 

We learned how to automatically save a value into a SQL database using ASP.Net WebMethod and jQuery Ajax. I hope this article is useful for all .NET beginners.
 

Up Next
    Ebook Download
    View all
    Learn
    View all