Save data to database without postback using jQuery ajax in ASP.NET

Category > ASP.NET || Published on : Thursday, February 11, 2016 || Views: 10178 || Save data to database without postback using jQuery ajax in ASP.NET


Introduction

Here Pawan Kumar will explain how to Save data to database without postback using jQuery ajax in ASP.NET

Description

In previous post I have explained How to find third highest salary in sql server., How to prevent input field from special character, How to display image on image selection using fileupload control in JQuery., Add TextBox Dynamically ASP.Net on Click ASP.Net Button, Mask UnMask Input Text jQuery Html, JavaScript Alert Message Dialog Box, and many more articles.

Now I will explain How to Save data to database without postback using jQuery ajax in ASP.NET

So follow the steps to learn Save data to database without postback using jQuery ajax in ASP.NET

Step 1: Create a new database with name "Test"

Step 2: Create a new table with name "Employee". You can use the below script:-

USE [test]
GO

/****** Object:  Table [dbo].[Employee]    Script Date: 02/11/2016 16:35:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Employee](
	[Name] [varchar](50) NULL,
	[Age] [varchar](50) NOT NULL,
	[Sex] [varchar](50) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

Step 3: Create a new website using Visual Studio 2010.

Step 4: Add a new webform and name it default.aspx.

Step 5: Add the following code to the aspx webpage

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
    <title>jQuery AJAX call to insert records to database</title>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnsubmit').click(function () {
                var name = $('#txtName').val();
                var age = $('#txtAge').val();
                var sex = $('#txtSex').val();
                $.ajax({
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    url: 'Default.aspx/InsertData',
                    data: "{'name':'" + name + "','age':'" + age + "','sex':'" + sex + "'}",
                    async: false,
                    success: function (response) {
                        $('#txtName').val(''); $('#txtAge').val(''); $('#txtSex').val('');
                        alert("Record saved successfully..!!");
                    },
                    error: function () {
                        alert("Error");
                    }
                });
            });
        });
    </script>

    <style type="text/css">
        #btnsubmit {
            text-align: center;
        }
    </style>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table align="center">
                <tr>
                    <td>Name  </td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server" ClientIDMode="Static"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Age  </td>
                    <td>
                        <asp:TextBox ID="txtAge" runat="server" ClientIDMode="Static"> </asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Sex </td>
                    <td>
                        <asp:TextBox ID="txtSex" runat="server" ClientIDMode="Static"> </asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <input type="button" id="btnsubmit" value="Submit" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Step 6: Addthe following code in Code Behind file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;

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

    }

    [WebMethod]
    public static string InsertData(string name, string age, string sex)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString);
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("Insert into Employee (Name,Age,Sex) values(@name,@age,@sex)", conn);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@name", name);
            cmd.Parameters.AddWithValue("@age", age);
            cmd.Parameters.AddWithValue("@sex", sex);
            cmd.ExecuteNonQuery();
            conn.Close();
            return "Success";
        }
        catch (Exception ex)
        {
            return "failure";
        }
    }
}

Conclusion:

So, In this tutorial we have learned, Save data to database without postback using jQuery ajax in ASP.NET

Download Source Codes