Image
One of the key features of Ajax is the XMLHttpRequest Object. It provides all the necessary methods and properties to a web application to communicate (or exchange data) with a server (any server).
Here, I’ll create a Web Service in Asp.Net, which has 2 web methods. The first method, after receiving an Ajax POST request, will add data to a table in SQL Server. The second method, will respond to an Ajax GET request by sending data to the client application.
So let’s first create a table in SQL Server.
Create a table named dbo.Students, with few columns in it.
CREATE TABLE Students ( ID int IDENTITY(1,1) PRIMARY KEY, Name varchar(255) NOT NULL, Address varchar(255), Age int );
The service that I am creating has two public methods namely addStudents() and getStudents().
If you are new to Asp.Net Web service, or forgot the whole procedure (it happens), follow these steps to create a web service in Asp.Net.
1) Create a new Asp.Net project.
2) To add a Web Service in your website, right click the website in the Solution explorer and select Add New Item ….
3) From the list of Templates select Web Service and click the Add button.
4) The default name of file will be WebService.asmx (do not change the name), which will be located at the root of your website. This process will also create a Class file with the same name but different extensions. (For C# and Vb.Net)
👉 Learn more on Asp.Net Web Services
Ok, let’s get on with the example.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { const string sConnString = "Data Source=DNA;Persist Security Info=False;" + "Initial Catalog=DNA_Classified;User Id=sa;Password=demo;Connect Timeout=30;"; [System.Web.Services.WebMethod()] public static string addStudents(string val) { string functionReturnValue = null; try { using (SqlConnection con = new SqlConnection(sConnString)) { string sQuery = null; sQuery = "INSERT INTO dbo.Students (Name, Address, Age)" + "VALUES (" + HttpUtility.UrlDecode(val) + ")"; using (SqlCommand cmd = new SqlCommand(sQuery)) { cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); functionReturnValue = "New student added."; } } } catch (Exception ex) { functionReturnValue = "There was an error"; } finally { } return functionReturnValue; } public class Students { public string id; public string Name; public string Address; public string Age; } [System.Web.Services.WebMethod()] [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json, UseHttpGet = true)] public static List<Students> getStudents() { List<Students> lstStudents = new List<Students>(); try { using (SqlConnection con = new SqlConnection(sConnString)) { SqlCommand objComm = new SqlCommand("SELECT *FROM dbo.Students", con); con.Open(); SqlDataReader reader = objComm.ExecuteReader(); while (reader.Read()) lstStudents.Add(new Students() { id = System.Convert.ToString(reader["ID"]), Name = reader["Name"].ToString(), Address = reader["Address"].ToString(), Age = System.Convert.ToString(reader["Age"]) }); con.Close(); } } catch (Exception ex) { } finally { } return lstStudents; } }
See the second method in the web service (in both C# and VB), where I have defined the ScriptMethod() with UseHttpGet = true and the response type as JSON.
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json, UseHttpGet = true)]
It clearly indicates the method is called from the client app using the Ajax GET method. Without defining the ScriptMethod(), the server will throw a 500 internal server error.
Option Explicit On Imports System.Data.SqlClient Partial Class _Default Inherits System.Web.UI.Page Const sConnString As String = "Data Source=DNA;Persist Security Info=False;" & _ "Initial Catalog=DNA_Classified;User Id=sa;Password=demo;Connect Timeout=30;" <System.Web.Services.WebMethod()> _ Public Shared Function addStudents(ByVal val As String) As String Try Using con As SqlConnection = New SqlConnection(sConnString) Dim sQuery As String sQuery = "INSERT INTO dbo.Students (Name, Address, Age)" & _ "VALUES (" & HttpUtility.UrlDecode(val) & ")" Using cmd As SqlCommand = New SqlCommand(sQuery) With cmd .Connection = con con.Open() cmd.ExecuteNonQuery() con.Close() addStudents = "New student added." End With End Using End Using Catch ex As Exception addStudents = "There was an error" Finally End Try Return addStudents End Function Public Class Students Public id As String Public Name As String Public Address As String Public Age As String End Class <System.Web.Services.WebMethod()> _ <Script.Services.ScriptMethod(ResponseFormat:=Script.Services.ResponseFormat.Json, UseHttpGet:=True)> _ Public Shared Function getStudents() As List(Of Students) Dim lstStudents As New List(Of Students)() Try Using con As SqlConnection = New SqlConnection(sConnString) Dim objComm As New SqlCommand("SELECT *FROM dbo.Students", con) con.Open() Dim reader As SqlDataReader = objComm.ExecuteReader() While reader.Read() lstStudents.Add(New Students() With { _ .id = CInt(reader("ID")), _ .Name = reader("Name").ToString(), _ .Address = reader("Address").ToString(), _ .Age = CDbl(reader("Age")) _ }) End While con.Close() End Using Catch ex As Exception Finally End Try Return lstStudents End Function End Class
Well, our web service is ready. Run it to see if every this is working fine. Now we can create an app to test the Ajax POST and GET methods in action.
I’ll add few controls on the web page.
<html> <body> <h3>Students Info</h3> <div style="padding:10px;border:solid 1px #999;"> <ul> <li>Name:</li><li><input type="text" id="name" /></li> <li>Address:</li><li><input type="text" id="address" /></li> <li>Age:</li><li><input type="text" id="age" /></li> </ul> <input type="button" id="submit" value="Submit" onclick="saveData()" /> </div> <div> <p><input type="button" id="btShow" value="Show Students" onclick="getData()" /></p> <p id="showData"></p> </div> </body> </html>
The Script with Ajax POST and GET methods
<script> let values = new Array(); let col = new Array() // Using Ajax POST method. let saveData = () => { const ele = document.getElementsByTagName('input'); // Loop through each element. for (let i = 0; i < ele.length; i++) { // Check the element type. if (ele[i].type == 'text') { // Now, store text value and id in arrays. if (ele[i].value != '') { values.push("'" + ele[i].value + "'"); col.push(ele[i].id); } } } if (values != '') { const oXHR = new XMLHttpRequest(); // Create XMLHttpRequest object. // Initiate request. oXHR.onreadystatechange = reportStatus; oXHR.open("POST", "http://localhost:4691/vb/default.aspx/addStudents", true); oXHR.setRequestHeader("Content-Type", "application/json"); let d = { val: escape(values) }; oXHR.send(JSON.stringify(d)); // Now send the request (with data); function reportStatus() { if (oXHR.readyState == 4) { // Check if request is complete. alert(this.responseText); // Clear the arrays. values = []; col = []; } } } else { alert("Fields cannot be empty.") } } // Using Ajax GET method. let getData = () => { // Create XMLHttpRequest object. const oXHR = new XMLHttpRequest(); // Initiate request. oXHR.onreadystatechange = reportStatus; oXHR.open("GET", "http://localhost:4691/vb/default.aspx/getStudents", true); oXHR.setRequestHeader("Content-Type", "application/json"); oXHR.send(); // Now send the request (without any data); function reportStatus() { // Check if request is complete. if (oXHR.readyState === XMLHttpRequest.DONE && oXHR.status === 200) { let studentData = JSON.parse(this.responseText); for (let i = 0; i < studentData.d.length; i++) { document.getElementById('showData').innerHTML += studentData.d[i].Name + ' ' + studentData.d[i].Address + ' ' + studentData.d[i].Age + '<br />'; } } } } </script>
I have defined two functions saveData() and getData() in the <script> section.
Ajax POST Method
The first function (saveData()) extracts values from each input box (or textbox) and makes a request to a Web Service method using Ajax POST.
The Ajax POST method is ideal for sending large amount of data to the server. It is also a secure method to send sensitive data to the server from a client app.
I am using XMLHttpRequest Object for the exchange of data between the web service that I have created and my application. All modern browsers support this object.
XMLHttpRequest Object Methods
It is important that you understand the methods of XMLHttpRequest Object.
1) onreadystatechange Property: Sets or retrieves the event handler for asynchronous requests. onreadystatechange property was first introduced in IE 7.
2) readyState Property: The readyState property will define the current state of request operation or the request made by XMLHttpRequest object.
Values of readyState Property
State
0
1
2
3
4
Description
Uninitialized. Not yet initialized, but an object is created.
The request has been setup. The object is created, send method not yet called.
We have sent a request.
The sent request is still in process.
The request is complete and ready to process further.
3) The open() Method: You must initialize the "XMLHttpRequest object" through the open() method. This method takes five parameters. However, I have used three parameters in my example above.
open ( Method, URL, Asynchronous, UserName, Password )
4) The send() Method: Call this method to send an http request. The send method accepts only one parameter called the data.
send ( data )
5) setRequestHeader() Method: You must pay attention is this method. I have used setRequestHeader() to define the type of data (JSON format) that is used to send a request to the web service.
oXHR.setRequestHeader("Content-Type", "application/json");
Ajax GET Method
The second function (getData()) sends an Ajax request to the Web Service for student details. Here I have used the GET method.
oXHR.open("GET", "http://localhost:4691/csharp/default.aspx/getStudents", true);
The methods that I have used are similar to the POST method example above. Accept, that the send() method does not have any value. It is simply requesting data.
Once request is completed, you can show the data on your web page using a table or simply populate a dropdown list with data or do whatever you want.
Alternatively, you can do the same using jQuery Ajax.