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 anythingpublic 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
Thanks a lot....
ReplyDeleteYou are welcome dear
DeleteU too chirag
ReplyDeleteThis page open in Mobile or Not?
ReplyDeleteHow it open in mobile?
What code will be add?
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
DeleteThis comment has been removed by the author.
ReplyDeletei copy paste code as it is , but its not working in my website
ReplyDeletei think you did not uncomment the red marked line .what i am highlighting in above section please check it
Deleteur code is not working frnd........
ReplyDeletei dont know wht is the prob can u plz explain
Can u give me your code to better clarify where is your actual fault
DeleteThis comment has been removed by the author.
ReplyDelete1.have you give this script inside your aspx page
ReplyDeletescript 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]
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.
ReplyDeleteBecz it is not finding the path properly.Just drag Your webservice to any page and copy that path.it will work fine
DeleteMake sure your Webservice path is correctly given(../../folder name if any)
ReplyDeleteI add form and web service under the root directory.. which means no separate folder for any ....
DeleteHi when i run my page with firebug it shows "NetworkError: 500 Internal Server Error - http://localhost:1701/sampletsk/WebService.asmx/insertdb"
ReplyDeletehere insertdb is a web method
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.
DeleteYou 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?
ReplyDeleteHello Usha You just try my another post
ReplyDeletehttp://shibashishdotnetocean.blogspot.in/2012/02/insert-data-in-sqlserver-database-using.html
hi this is not working.
ReplyDeletei 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
go for the alternative way otherwise please check that [System.Web.Script.Services.ScriptService] is unchecked or not in webservice.
Deleteplease 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
how to implement the above ASPX Code in html5 page please help us.
ReplyDeletethanks and Regards,
Gowtham