Sunday, February 19

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 Shibashish Mohanty's Previous 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.
////Make Sure The above Red Marked Line is uncomment or not if not then uncomment it otherwise you dont get anything

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

    public WebService () {

        //Uncomment the following line if using designed components 

    public string HelloWorld() {
        return "Hello World";

    string constr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    int rowsInserted = 0;
    public string ReceiveWebService(string name, string email, string phone, string address)
        using (SqlConnection conn = new SqlConnection(constr))
            string sql = string.Format(@"INSERT INTO [SampleTestDB]([Name] , [Email] , [Phone] ,[Address]) VALUES ('{0}','{1}','{2}','{3}')", name, email, phone, address);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;
            rowsInserted = cmd.ExecuteNonQuery();
            cmd = null;
        return string.Format("Thank you ,{0} number of rows inserted!", rowsInserted);

ASPX Code:

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

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

<html xmlns="">
<head id="Head1" 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: "WebService.asmx/ReceiveWebService",
            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">



//I have taken one sql server database in App.Data Folder As shown Above in Diagram

Here Is My Web.Config ConnectionString:-

<?xml version="1.0"?>
  For more information on how to configure your ASP.NET application, please visit
    <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>

<compilation debug="true" targetFramework="4.0"/>
    <behavior name="">
     <serviceMetadata httpGetEnabled="true" />
     <serviceDebug includeExceptionDetailInFaults="false" />
  <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

If some one found some error plz inform me i am glad to help you but you just remember you have to follow the instruction what i boldly declared after all if you are facing trouble then you can try this following one.
Click To View The Alternative Way Of this Tutorial
Thanks Shibashish mohanty


  1. This page open in Mobile or Not?
    How it open in mobile?
    What code will be add?

    1. Anil thanks to view my page actually i did not checked in mobile but i will check it very soon for you.Thanks a lot

  2. This comment has been removed by the author.

  3. i copy paste code as it is , but its not working in my website

    1. i think you did not uncomment the red marked line .what i am highlighting in above section please check it

  4. ur code is not working frnd........

    i dont know wht is the prob can u plz explain

    1. Can u give me your code to better clarify where is your actual fault

  5. This comment has been removed by the author.

  6. 1.have you give this script inside your aspx page
    script src=""> /script
    2.have you uncomment the following line inside your web service

  7. hi i did this method as like you showed . but web service can not invoked from jquery . but separately run web service it work fine. is there any other points to add more.

    1. Becz it is not finding the path properly.Just drag Your webservice to any page and copy that will work fine

  8. Make sure your Webservice path is correctly given(../../folder name if any)

    1. I add form and web service under the root directory.. which means no separate folder for any ....

  9. Hi when i run my page with firebug it shows "NetworkError: 500 Internal Server Error - http://localhost:1701/sampletsk/WebService.asmx/insertdb"

    here insertdb is a web method

    1. Just change this type:'POST' to type:'GET'.i think it will resolve.Please responce me after you get the output.You can tell me through my contact number.Feel free to call me.

  10. You make a POST request to the server, but if you do not pass any data (everything is in the query string). Perhaps it should be a GET request instead?

  11. Hello Usha You just try my another post

  12. hi this is not working.
    i have created a simple application but its not working yet.
    ya one thing that i have created the table in the sql server.
    help me for this

    1. go for the alternative way otherwise please check that [System.Web.Script.Services.ScriptService] is unchecked or not in webservice.
      please give proper path url: "WebService.asmx/ReceiveWebService",
      you can try to provide like
      url: "../WebService.asmx/ReceiveWebService",
      url: "~/WebService.asmx/ReceiveWebService",
      url: "../FolderName/WebService.asmx/ReceiveWebService"
      Ithink it will resolve

  13. how to implement the above ASPX Code in html5 page please help us.

    thanks and Regards,


Please don't spam, spam comments is not allowed here.

shibashish mohanty