JavaScript Ajax POST and GET method Example

← PrevNext →

Ajax, as you know stands for Asynchronous JavaScript and XML, which allows web applications (client side) to send and receive data from a server, asynchronously. Ajax can be used with any framework or library like jQuery. You can even use Ajax with plain JavaScript. In this post, I’ll show you how to use Ajax POST and GET methods in JavaScript to send requests to Asp.Net Web Service methods.


JavaScript Ajax POST and GET methods example

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 in SQL Server

Create a table named dbo.Students, with few columns in it.

    Name varchar(255) NOT NULL,
    Address varchar(255),
    Age int
The Web Service (C#)

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
AutoComplete textbox in jQuery

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;";

    public static string addStudents(string val)
        string functionReturnValue = null;
            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;


                    functionReturnValue = "New student added.";
        catch (Exception ex)
            functionReturnValue = "There was an error";
        {        }

        return functionReturnValue;

    public class Students
        public string id;
        public string Name;
        public string Address;
        public string Age;

    [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>();

            using (SqlConnection con = new SqlConnection(sConnString))
                SqlCommand objComm = new SqlCommand("SELECT *FROM dbo.Students", con);

                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"])

        catch (Exception ex)

        {      } 

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

The Web Service (Visual Basic)
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
            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


                        addStudents = "New student added."
                    End With
                End Using
            End Using
        Catch ex As Exception
            addStudents = "There was an error"
        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)()

            Using con As SqlConnection = New SqlConnection(sConnString)

                Dim objComm As New SqlCommand("SELECT *FROM dbo.Students", con)

                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

            End Using

        Catch ex As Exception


        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.

The Markup

I’ll add few controls on the web page.

    <h3>Students Info</h3>
    <div style="padding:10px;border:solid 1px #999;">
            <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>

        <input type="button" id="submit" value="Submit" onclick="saveData()" />

        <p><input type="button" id="btShow" value="Show Students" onclick="getData()" /></p>
        <p id="showData"></p>

The Script with Ajax POST and GET methods

    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 + "'");      

        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.

                    // 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 />';

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




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.

Happy coding. 🙂

← PreviousNext →