Insert Data Using jQuery Ajax in C# [Database MS SQLServer]


Insert data with jQuery ajax in : Here in this article will see how to insert data using jquery ajax C#. i.e. A simple example for adding records into the database ( MS SQL SERVER) using jquery ajax in C#. In my previous post have also explained how to fetch record from the database using jquery ajax in as JSON result .i.e ( web method return JSON result).

Now in this article, we mainly focus on how to insert or add a record into the database without page postback, and this can be done with jquery AJAX method. We make an ajax call from client side which sends parameters (data) to the server-side, and on server-side we save these values into our database.

On server-side, we can handle this in many different ways such as by using Generic Handlers (ashx file), by using WebMethod (ASMX file), by using WCF services or with Web API.

Here will see a simple example to insert data into the database using jquery ajax call web method with parameters.


Steps to insert data using ajax in C#.

  1. Download and import jQuery library.
  2. Add HTML Markup.
  3. Create Class object.
  4. Code behind: Create Webmethod (to insert records).
  5.  jQuery: Calling jquery Ajax method.

Am assuming you are aware of WebMethod (ASMX file). So let's make this post simple here on the server-side (C#) will insert record using WebMethod.

# Download and import jQuery library.

As we are using jquery ajax method so before writing any code, first we will download and include latest jQuery file into our Webform (default.aspx page).You can host the jQuery file on the server, or you can direct use the Google-hosted jQuery library.

So after that, our Webpage head tag looks like as written below.

 <script src="">

# Adding HTML Markup: Input tags whose values get inserted into the database [MS Sqlserver].

Here am adding some textboxes and a button tag in the webform ( default.aspx ). And on button click, will make jquery ajax method. In short will pass multiple parameters in ajax call jquery to save these parameters with server-side code.

So this is how our HTML looks like as written below.

                <td> First Name : </td>
                <td><input id="txtFirstName" type="text" /> </td>
                <td>Last Name :  </td>
                <td><input id="txtLastName" type="text" /> </td>
                <td>Location :  </td>
                <td><input id="txtLocation" type="text" />  </td>
                <td><button id="btnAddRecord">Add Record</button>
                    <span id="msg"></span>
As by looking at the HTML structure, you already got the idea, what we are going to save. Yes, we are going to save UserDetails i.e. Firstname, LastName, and its Location into our database MS SQL Server.

# Create Class Object:

As we need to pass JSON object from Client side to Server side, so we have to encode our JavaScript Object to JSON. And Decoding can be done on Server side. So that Javascript object can be converted into a C# class object. Let's create a C# Class.

Here in our case, we are going to save user details, so we created a new class named as userDetails having properties as firstname, lastname, location and also remember similar structure will be used for Javascript Object on client-side

public class userDetails
   public string firstName;
   public string lastName;
   public string location;

# Code-behind: Create a Webmethod (which use to save records)

So far we are ready with HTML structure and with class object userDetails, so now let write a webmethod which will save the data into the database and we call this webmethod (Webservice) from client-side via jquery ajax.

This is how our Webmethod code looks like as written below:

public string addNewUser(userDetails userDetails)
		using (SqlConnection con = new SqlConnection(cn.ConnectionString))
			using (SqlCommand cmd = new SqlCommand())
				cmd.CommandText = "insertNewUser";
				cmd.CommandType = CommandType.StoredProcedure;
				cmd.Connection = con;

				cmd.Parameters.AddWithValue("@firstName", userDetails.firstName);
				cmd.Parameters.AddWithValue("@lastName", userDetails.lastName);
				cmd.Parameters.AddWithValue("@location", userDetails.location);
			} con.Close();
		return "success";
	catch (Exception ac)
		return "Error";

Note: To avoid SQL Injections, I always use parameterized query or using Stored procedure at my work. Check what is sql injection and how to prevent it? Best practice would be to use parameterized query to perform CRUD operations instead simple SQL statement

# Calling jquery Ajax method, and post / insert data on the server.

Please have a close look at this part as it's an essential part of this article because jquery ajax method is mostly used in all the WebApplication. It's good to have a nice understanding of it, so you can play with it while working on your project.

Now on button click we call webmethod from jquery with parameters, and these parameters (data) save into the database. You may notice we send parameters as JSON object, as we already created the similar class object on the server-side.

This is how our jquery ajax method looks like as written below, which calls the webmethod addNewUser which we created earlier on the server-side.
  $(document).ready(function () {

            $("#btnAddRecord").on('click', function (e) {

                var userDetails = {};

                userDetails.firstName = $("#txtFirstName").val();
                userDetails.lastName = $("#txtLastName").val();
                userDetails.location = $("#txtLocation").val();

                var jsonData = JSON.stringify({
                    userDetails: userDetails

                    type: "POST",
                    url: "Ajax_function/ajax_update.asmx/addNewUser",
                    data: jsonData,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    error: OnErrorCall

                function OnSuccess(response) {
                    var result = response.d;
                    if (result == "success") {
                        $("#msg").html("New record addded successfully  :)").css("color", "green");

                function OnErrorCall(response) {
                    $("#msg").html("Error occurs  :(").css("color", "red");


Yes, it's done now, Hit the button and your ajax method gets called.

Note: These 2 most common errors occur while working with Webmethod

  1. Invalid web service call, missing value for parameter:
  2. Unknown web method error
Error 1: Occurs when the JSON object that we are passing to the server doesn’t have the same parameter name as per the C# web method. i.e our C# class object name should be same as our Javascript object. Error 2: This error occurs most probably if you have set wrong webmethod name or wrong webmethod URL or else if the webmethod was written on Webpage i.e., (.ASPX page) then you need to declare it as Static.

Conclusion: By the end of this article you were able to call webmethod from jquery ajax. This article explains in C# with the combination of jquery ajax method and Webservice (ASMX) webmethod How to insert or save data using jquery in c#. That is without page postback we can able to save data into the database MS SQL in our C# Web Application.

You must also check these articles:

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.

Post Comment

Your email address will not be published. Required fields are marked *