How to insert data in database using jquery
#1. Configure your web.config file. Because of start scripting services.
#2. Make a page with html controls.
First one: Text boxes which can contain the data to be insert in database
Second one: Button control which click event insert the in the database using jquery. <head runat="server">
<title>How to add data in database using Jquery</title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
var name = $('#txtName').val();
var age = $('#txtAge').val();
$.ajax({
type: "POST",
url: "AjaxService.asmx/AddData",
data: "{'name':'" + name + "','age':'" + age + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
$("#txtName").val() = "";
$("#txtAge").val() = "";
alert("Hello");
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Enter your name :
</td>
<td>
<input type="text" id="txtName" />
</td>
</tr>
<tr>
<td>
Enter your Age :
</td>
<td>
<input type="text" id="txtAge" />
</td>
</tr>
<tr>
<td>
<input type="button" id="btnSubmit" value="Submit" />
</td>
</tr>
</table>
</div>
</form>
</body>
#3. Make a .asmx file where you write the code to database connectivity.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data.SqlClient;
using System.Configuration;
/// <summary>
/// Summary description for AjaxService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService()]
public class AjaxService : System.Web.Services.WebService {
public AjaxService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public void AddData(string name, string age)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("Insert into InsertData(Name,Age) Values(@name,@age)",con);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@age", age);
cmd.ExecuteNonQuery();
con.Close();
}
}
Note: This code is for add data into database using jquery.
Without scripting services this will not run properly. So configure you web.config file to start scripting services.
#4. Create Database in ms sql server 2005
Create Database Test
Create Table InsertData(Name varchar(20),Age varchar(20))
#5. Thanks. If you like this then give me comment.
Download Full Code : http://rapidshare.com/files/425720577/JavaScriptUsingJquery.rar
No comments:
Post a Comment