ASP.NET - Data insertion using jquery AJAX

The main idea behind this article is to insert data using jQuery AJAX to avoid postback. AJAX offers users a seamless way to work with your interface, no waiting for whole pages to load. jQuery has a set of tools to make it super simple to implement.

Most everyone knows what iAJAX is. But for the beginners i would like to provide some information regarding the AJAX.
What is AJAX?
AJAX is a short hand for asynchronous JavaScript and XML.  Which plainly means that instead of waiting for the whole page to load, you can load only what you need to.  So if you only need to update one small text part of your site, you don’t have to worry about loading everything else on that page.  A vast majority of sites use this technology now.  Probably one of the most popular uses is an auto complete feature for the search box at Google and Yahoo.
If you see another term XHR, which is shorthand for XML HTTP request, it’s the same thing. Don’t be afraid of this jargon; AJAX is not rocket science.

   1.
In Gmail, switch from inbox to draft. Part of the page is changed, but the page is not refreshed. You remain on the same page. Url has not changed (except for the #draft at the end of the url, but that’s still the same webpage).
   2.
In Google Reader, select a feed. The content changes, but you are not redirected to another url.
   3.
In Google Maps, zoom in or zoom out. The map has changed, but you remain on the same page.

The key to AJAX’s concept is “asynchronous”. This means something happens to the page after it’s loaded. Traditionally, when a page is loaded, the content remains the same until the user leaves the page. With AJAX, JavaScript grabs new content from the server and makes changes to the current page. This all happena within the lifetime of the page, no refresh or redirection is needed.

There are several things that we could build that I have tried out to insert data using jQuery AJAX.
For beginners please visit this link for Web Methods in ASP.NET.

Here i have used web methods to call the server side method using jQuery. I have given the link of the source code which contains the screen shots and DB Scripts.
The code as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataInsertion.aspx.cs" Inherits="DataInsertion" %>

PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    
<title>Data insertion title>
    
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js">script>
    
<script type="text/javascript">
        $(document).ready(function () {
             GetID();
             $(
'#btnSave').click(function () {
                var s = validateFields();
                 
if (s) {
                    $.ajax({
                        type:
"POST",
                        url:
"DataInsertion.aspx/SaveData",
                        data:
'{firstName:"' + $('#tbFName').val() + '",lastName:"' + $('#tbLName').val() + '"}',
                        contentType:
"application/json; charset=utf-8",
                        success: OnSuccess,
                        failure: function (response) {
                            alert(response.d);
                        }
                    });
                    function OnSuccess(response) {
                          
if (response.d) {
                              alert(
"Successfully inserted !");
                            GetID();
                        }

                    }
                }
            });
        });

        function validateFields() {
            var tbFName = $(
'#tbFName').val();
            var tbLName = $(
'#tbLName').val();
             
if (tbFName == "") {
                 alert(
'Enter first name');
                 
return false;
            }
            
else if (tbLName == "") {
                 alert(
'Enter last name');
                 
return false;
            }
            
else {
                 
return true;
            }
        }
        function GetID() {
             $(
'#tbFName').val('');
            $(
'#tbLName').val('');
            $.ajax({
                type:
"POST",
                url:
"DataInsertion.aspx/GetID",
                 
// data: '{id: "' + $("#tbId").val() + '" ,firstName:"' + $('#tbFName').val() + '" ,lastName:"' + $('#tbLName').val() + '}',
                contentType:
"application/json; charset=utf-8",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }
            });
            function OnSuccess(response) {
                 $(
'#tbId').val(response.d);
                 $(
'#tbId').attr('readOnly', true);
            }
        }
    
script>
head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
<table>
            
<tr>
                 
<td>
                     ID:
                 
td>
                 
<td>
                     
<asp:TextBox ID="tbId" runat="server">asp:TextBox>
                 
td>
            
tr>
            
<tr>
                 
<td>
                     FirstName:
                 
td>
                 
<td>
                     
<asp:TextBox ID="tbFName" runat="server">asp:TextBox>
                 
td>
            
tr>
            
<tr>
                 
<td>
                     LastName:
                 
td>
                 
<td>
                     
<asp:TextBox ID="tbLName" runat="server">asp:TextBox>
                 
td>
            
tr>
        
table>
        
<input type="button" value="Save Data" id="btnSave" />
    
div>
    
form>
body>
html>
The Code behind is given below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class DataInsertion : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    
public static bool SaveData(string firstName, string lastName)
    {
        String connectionString = ConfigurationManager.ConnectionStrings[
"TESTDB"].ConnectionString;
        bool result =
false;
        
using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand cmd =
new SqlCommand();
            cmd.Connection = connection;
            cmd.CommandText = String.Format(
"insert into Hemanth_DB.dbo.PersonName(FirstName,LastName) values ('{0}','{1}')", firstName, lastName);
            cmd.CommandType = CommandType.Text;
             connection.
Open();
            int count = cmd.ExecuteNonQuery();
             
if (count > 0)
            {
                result =
true;
            }
            
else
            {
                result =
false;
            }
        }
         
return result;
    }
    [WebMethod]
    
public static int GetID()
    {
        int rowId;
        String connectionString = ConfigurationManager.ConnectionStrings[
"TESTDB"].ConnectionString;
        
using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand cmd =
new SqlCommand();
            cmd.Connection = connection;
            cmd.CommandText =
"select MAX(id)+1 from Hemanth_DB.dbo.PersonName";
            cmd.CommandType = CommandType.Text;
             connection.
Open();
            rowId = (int)cmd.ExecuteScalar();
         }
        
return rowId;
    }
    [WebMethod]
    
public static bool Upsert()
    {
         
return true;
    }
}


The source code is provided in this link:
InsertDataUsingAJAX

Any suggestion regarding my article are
welcome.
Thank you all.

Popular posts from this blog

Exporting to excel from a custom class object using C#.NET

Get the Clicked Cell Value and Column Name of GridView in ASP.NET

How to apply watermark to the textbox and dropdownlist?