Introduction
In this blog, we will learn how to insert and retrieve data using jQuery Ajax in asp.net. We will create a web service and consume that web service in our project with the help of jQuery Ajax.
Step 1
Create a database in the SQL server of your choice.
- CREATE TABLE [dbo].[tblEmployees](
- [ID] [int] IDENTITY(1,1) NOT NULL,
- [Name] [nvarchar](50) NULL,
- [Gender] [char](10) NULL,
- [Phone] [nvarchar](50) NULL,
- [Email] [nvarchar](50) NULL,
- [Age] [int] NULL,
- [Salary] [nvarchar](50) NULL,
- CONSTRAINT [PK_tblEmployees] PRIMARY KEY CLUSTERED
- (
- [ID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
-
- CREATE procedure [dbo].[spAddNewEmployee]
- (
- @Name nvarchar(50),
- @Gender char(10),
- @Phone nvarchar(50),
- @Email nvarchar(50),
- @Age int,
- @Salary nvarchar(50)
- )
- as
- begin
- insert into tblEmployees(Name,Gender,Phone,Email,Age,Salary)
- values(@Name,@Gender,@Phone,@Email,@Age,@Salary)
- end
-
- CREATE procedure [dbo].[spGetEmployees]
- as
- begin
- select ID,Name,Gender,Phone,Email,Age, Salary from tblEmployees
- end
Step 2
Add code in the webconfig file:
- <connectionStrings>
- <add name="DBCS" connectionString="data source=FARHAN\SQLEXPRESS; database=JQueryDB; integrated security=SSPI;" providerName="System.Data.SqlClient"/>
- </connectionStrings>
- <system.web>
- <webServices>
- <protocols>
- <add name="HttpGet"/>
- </protocols>
- </webServices>
- </system.web>
Step 3
Create class -- right click on new item, choose class, give the name employee.cs:
- public class Employee
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public string Gender { get; set;}
- public string Phone { get; set; }
- public string Email { get; set; }
- public int Age { get; set; }
- public string Salary { get; set; }
- }
Step 4
Create web service and give name as EmployeeService.asmx
Add namespace
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Serialization;
- [WebMethod]
- public void AddEmployee(Employee emp)
- {
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spAddNewEmployee", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.Add(new SqlParameter()
- {
- ParameterName = "@Name",
- Value = emp.Name
- });
- cmd.Parameters.Add(new SqlParameter()
- {
- ParameterName = "@Gender",
- Value = emp.Gender
- });
- cmd.Parameters.Add(new SqlParameter()
- {
- ParameterName = "@Phone",
- Value = emp.Phone
- });
- cmd.Parameters.Add(new SqlParameter()
- {
- ParameterName = "@Email",
- Value = emp.Email
- });
- cmd.Parameters.Add(new SqlParameter()
- {
- ParameterName = "@Age",
- Value = emp.Age
- });
- cmd.Parameters.Add(new SqlParameter()
- {
- ParameterName = "@Salary",
- Value = emp.Salary
- });
- con.Open();
- cmd.ExecuteNonQuery();
- }
- }
- [WebMethod]
- public void GetAllEmployees()
- {
- List<Employee> listEmployee = new List<Employee>();
- string CS=ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using(SqlConnection con=new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spGetEmployees", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- SqlDataReader rdr = cmd.ExecuteReader();
- while(rdr.Read())
- {
- Employee employee = new Employee();
- employee.ID = Convert.ToInt32(rdr["ID"]);
- employee.Name = rdr["Name"].ToString();
- employee.Gender = rdr["Gender"].ToString();
- employee.Phone = rdr["Phone"].ToString();
- employee.Email = rdr["Email"].ToString();
- employee.Age = Convert.ToInt32(rdr["Age"]);
- employee.Salary = rdr["Salary"].ToString();
-
- listEmployee.Add(employee);
- }
- }
- JavaScriptSerializer js = new JavaScriptSerializer();
- Context.Response.Write(js.Serialize(listEmployee));
- }
Step 5
Add web, right click on project and add new item, choose web form, give it a name.
Add scripts and styles in the head section:
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
- <script src="employee.js"></script>
Step 6 - Create script file employee.js
Write script to insert and retrieve data into the database:
- $(document).ready(function () {
- var employee = {};
- employee.Name = $('#txtName').val();
- employee.Gender = $('#ddlGender').val();
- employee.Phone = $('#txtPhone').val();
- employee.Email = $('#txtEmail').val();
- employee.Age = $('#txtAge').val();
- employee.Salary = $('#txtSalary').val();
-
- $.ajax({
- url: 'EmployeeService.asmx/AddEmployee',
- method: 'post',
- data: '{emp: ' + JSON.stringify(employee) + '}',
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function () {
- getAllEmployees();
- console.log(data);
- },
- error: function (err) {
- console.log(err);
- }
- });
-
- function getAllEmployees() {
- $.ajax({
- url: 'EmployeeService.asmx/GetAllEmployees',
- dataType: "json",
- method: 'GET',
- success: function (data) {
- var employeeTable = $('#employee tbody');
- employeeTable.empty();
-
- $(data).each(function (index, emp) {
- employeeTable.append('<tr><td>' + emp.ID + '</td><td>'
- + emp.Name + '</td><td>' + emp.Gender + '</td><td>'
- + emp.Phone + '</td><td>' + emp.Email + '</td><td>'
- + emp.Age + '</td><td>' + emp.Salary + '</td></tr>');
- });
- },
- error: function (err) {
- console.log(err);
- }
- });
- }
- });
Step 7 - Design HTML web form
Step 8 - Run project ctr+F5
Final output