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 = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
////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 
        //InitializeComponent(); 
    }


    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }


    string constr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    int rowsInserted = 0;
    [WebMethod]
    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;
            conn.Open();
            rowsInserted = cmd.ExecuteNonQuery();
            conn.Close();
            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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></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();


        $.ajax({
            type: "POST",
            url: "WebService.asmx/ReceiveWebService",
            data: "{ 'name': '" + name + "','email': '" + email + "', 'phone': '" + phone + "','address':'" + addr + "'}",
            contentType: "application/json",
            async: false,
            success: function (data) {
                $('#message').text(data.d);
            }
        });
    }


</script>
</head>
<body>
<form id="form1" runat="server">
<div>
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">


</span>


</div>
</form>
</body>
</html>




//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
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
<connectionStrings>
  
    <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>

  </connectionStrings>
 <system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
 <system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="">
     <serviceMetadata httpGetEnabled="true" />
     <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
   </serviceBehaviors>
  </behaviors>
  <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
 </system.serviceModel>
</configuration>

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

23 comments:

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

    ReplyDelete
    Replies
    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

      Delete
  2. This comment has been removed by the author.

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

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

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

    i dont know wht is the prob can u plz explain

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

      Delete
  5. This comment has been removed by the author.

    ReplyDelete
  6. 1.have you give this script inside your aspx page
    script src="http://code.jquery.com/jquery-latest.min.js"> /script
    2.have you uncomment the following line inside your web service
    [System.Web.Script.Services.ScriptService]

    ReplyDelete
  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.

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

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

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

      Delete
  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

    ReplyDelete
    Replies
    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.

      Delete
  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?

    ReplyDelete
  11. Hello Usha You just try my another post
    http://shibashishdotnetocean.blogspot.in/2012/02/insert-data-in-sqlserver-database-using.html

    ReplyDelete
  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

    ReplyDelete
    Replies
    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

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

    thanks and Regards,
    Gowtham

    ReplyDelete

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

.

ShibashishMnty
shibashish mohanty