Insert data method using jQuery Ajax JSON Call in asp.net C# with sample code

jQuery is most famous JavaScript library to work handle JavaScript events easily. You can download jQuery or get CDN jQuery Version to include it in your project.
Mostly when we are using Asp.net application we always preferred postback events for submitting form data. Now every year technology changes as per new requirement. Now a day you can see most famous site preferred submit form without any postback. To prevent and handle postback while submitting data We come up with jQuery AJAX based form submitting.Using AJAX callback you can call server side events of any page. AJAX use JSON format data while forwarding the POST request. For using AJAX Call for submitting data in asp.net, you must include jQuery to handle all events.

We use simple database structure to understand very easily. You can use your own if you are better in coding.

Example of jQuery AJAX JSON Call in asp.net C#


Database Structure for our example

Column NameData Type
IDint(Primary Key)
First Namevarchar(50)
Last Namevarchar(50)
Cityvarchar(30)
EmailIDvarchar(100)

CREATE TABLE Sample(
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [FirstName] [varchar](50) NULL,
 [LastName] [varchar](50) NULL,
 [City] [varchar](30) NULL,
 [EmailID] [varchar](100) NULL)
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Example of jQuery AJAX Callback using Asp.net C#</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
  
</head>

<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>First Name :</td>
                    <td>
                        <input type="text" id="txtFirstName" />
                    </td>
                </tr>
                <tr>
                    <td>Last Name :</td>
                    <td>
                        <input type="text" id="txtLastName" />
                    </td>
                </tr>
                <tr>
                    <td>City :</td>
                    <td>
                          <input type="text" id="txtCity" />
                    </td>
                </tr>
                <tr>
                    <td>EmailID :</td>
                    <td>
                          <input type="text" id="txtEmailID" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="button" id="btnSubmit" value="Submit" />
                        <label id="lblmsg" style="color:green" />
                    </td>
                </tr>
            </table>
            <asp:GridView ID="gvData" AutoGenerateColumns="true" runat="server"></asp:GridView>
        </div>
    </form>
      <script type="text/javascript">
          $(function () {
              $('#btnSubmit').click(function () {
                  $.ajax({
                      type: "POST",
                      contentType: "application/json; charset=utf-8",
                      url: "Default.aspx/InsertData",
                      dataType: "json",
                      data: "{'FirstName':'" + $('#txtFirstName').val() + "','LastName':'" + $('#txtLastName').val() + "','City':'" + $('#txtCity').val() + "','EmailID':'" + $('#txtEmailID').val() + "'}",
                      success: function (data) {
                          var obj = data.d;
                          if (obj == 'true') {
                              $('#txtFirstName').val('');
                              $('#txtLastName').val('');
                              $('#txtCity').val('');
                              $('#txtEmailID').val('');
                              $('#lblmsg').html('Data Inserted Successfully');
                          }
                      },
                      error: function (result) {
                          alert(result);
                      }
                  });
              });
          });
    </script>
</body>
</html>

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }
    [WebMethod]
    public static string InsertData(string FirstName, string LastName, string City, string EmailID)
    {
        string retMessage = string.Empty;
        string ConnectionString= "Enter Your Connection String";
        using (SqlConnection con = new SqlConnection(ConnectionString))
        {
            string Query = "insert into Sample(FirstName, LastName, City, EmailID) values(@FirstName,@LastName,@City,@EmailID)";
            using (SqlCommand cmd = new SqlCommand(Query,con))
            {
                con.Open();
                cmd.Parameters.Add("@FirstName", FirstName);
                cmd.Parameters.Add("@LastName", LastName);
                cmd.Parameters.Add("@City", City);
                cmd.Parameters.Add("@EmailID", EmailID);

                int AffectedRow = cmd.ExecuteNonQuery();
                if (AffectedRow == 1)
                {
                    retMessage = "true";
                }
                else
                {
                    retMessage = "false";
                }
            }
            return retMessage;
        }
    }
}
Demo
insert-update-select-using-jquery-json-ajax-callback-in-aspnet-dotnetspan
Download Sample Code