Insert Data using JSON, ASP.NET Web services and jQuery

In previous post, we saw how to retrieve data from database in JSON and display in tabular format using jQuery AJAX (Click here to read the article).

Today we will look at how to create a form which will take input from user and insert it into the database using jQuery AJAX call.

Record in Database:


Web service code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Web.Configuration;

using System.Data;

using System.Data.SqlClient;



[WebService(Namespace = "")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.


public class MultipleUpdateWebService : System.Web.Services.WebService {

// getting connection string

string conStr=WebConfigurationManager.ConnectionStrings["SampleTestDBConnectionString1"].ConnectionString;

int rowsInserted = 0;


public string ReceiveUpdatesWebservice(string name,string email, string phone, string address) {

// Creating Sql Connection

using (SqlConnection conn=new SqlConnection(conStr))


// Creating insert statement

string sql = string.Format(@"INSERT INTO [SampleTestDB].[dbo].[SampleInfoTable]










SqlCommand cmd = new SqlCommand();

cmd.Connection = conn;

cmd.CommandText = sql;

cmd.CommandType = CommandType.Text;




cmd = null;




return string.Format("Thank you, {0} number of rows inserted!",rowsInserted);





ASPX Code:

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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">


<html xmlns="">

<head runat="server">


<script type="text/javascript" src=""></script>

<script type="text/javascript">

function CallService() {

// Creating variables to hold data from textboxes

var name = $('#_txtname').val();

var email = $('#_email').val();

var phone = $('#_phone').val();

var addr = $('#_addr').val();



type: "POST",

url: "MultipleUpdateWebService.asmx/ReceiveUpdatesWebservice",

data: "{ 'name': '" + name + "','email': '" + email + "', 'phone': '" + phone + "','address':'" + addr + "'}",

contentType: "application/json",

async: false,

success: function(data) {








<form id="form1" runat="server">


Name: <asp:TextBox ID="_txtname" runat="server"></asp:TextBox><br />

Email: <asp:TextBox ID="_email" runat="server"></asp:TextBox><br />

Phone: <asp:TextBox ID="_phone" runat="server"></asp:TextBox><br />

Address: <asp:TextBox ID="_addr" runat="server"></asp:TextBox><br />

<input id="_btnSubmit" type="button" value="Submit" onclick="CallService();" />

<span id="message">








Tags: , , , ,

AJAX | ASP.NET | jQuery