CinnamonRii
CinnamonRii

Reputation: 156

How to call an ASP.NET WebMethod via AJAX (Native JS)

Is there a way to call a WebMethod using native JS AJAX?

Similar to:

           $.ajax({
                    type: "POST",
                    url: "AssignAdditional_Equip.aspx/getEquipListing",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var result = JSON.parse(data.d);
                        console.log(result);
                    },
                    error: function (response) {
                        alert(response);
                    }
                });  

The code below is my attempt:

var requestVar = new XMLHttpRequest();
requestVar.open('GET', 'AssignAdditional_Equip.aspx/getEquipListing');
requestVar.onload = function () {
    if (requestVar.status === 200) {
        console.log(requestVar.responseText);
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
requestVar.send();

Edit: Here's my webmethod on codebehind to clear up some confusion

    <WebMethod>
Public Shared Function getEquipListing()
    Dim equipType_Options As New List(Of String)
    Dim serializer As New JavaScriptSerializer
    Dim sqlConn As New SqlConnection
    Dim reader As SqlDataReader

    sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings("ITSGinventory").ConnectionString

    Dim sqlCmd As New SqlCommand("SELECT DISTINCT(Equipment_Type) FROM tbl_Equipments ORDER BY Equipment_Type ASC", sqlConn)

    sqlConn.Open()

    reader = sqlCmd.ExecuteReader

    While reader.Read()
        equipType_Options.Add(reader("Equipment_Type"))
    End While

    sqlConn.Close()
    sqlConn.Dispose()

    Return serializer.Serialize(equipType_Options)
End Function

The webmethod is supposed to return a serialized list of strings. Using JQuery, it works as intended. But my native AJAX approach returns the HTML markup of the page instead of the string values. Am I doing it wrong?

Upvotes: 0

Views: 1093

Answers (2)

CinnamonRii
CinnamonRii

Reputation: 156

Okay, so after reading, researching and rewriting my code, I was able to make this work. I only needed to add xmlHttp.setRequestHeader('Content-Type', 'application/json'); and was able to get a response from my WebMethod. LOL.

Always keep this in mind when trying to call/invoke ASP.NET WebMethods that has a JSON return type.

Upvotes: 0

alanextar
alanextar

Reputation: 1314

I think you can use fetch function with json method to extract from http response. Well explained how to use here. For example:

let response = await fetch(url);
if (response.ok) { // if HTTP-status is 200-299
  let json = await response.json();
} else {
  alert("HTTP-Error: " + response.status);
}

Upvotes: 1

Related Questions