0

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?

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the suggestion! This worked when I tried experimenting with it, however, I needed something backwards compatible with old browsers. So, I'll stick with XMLHttpRequest for a while. Fetch API is a good solution for newer browsers going forward.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.