Utilizing XmlHttpRequest and Pure JavaScript to Trigger WebMethods

Struggling with an apparently simple task that has left me completely stumped. After exhausting all my research efforts, I've hit a dead end and decided to seek help from the community.

Let me outline the issue:

  • An ASPX page (Q2.aspx) decorated with the WebService, WebServiceBinding, and ScriptService attributes.
  • This page includes a method called GetAllContacts with the WebMethod attribute returning JSON data as a string.
  • An HTML page with JavaScript that uses XmlHttpRequest object to call the GetAllContacts WebMethod and transform the data into an HTML table.
  • Confirmed that the Web.Config file has the proper protocol handlers for HttpGet and HttpPut under the System.Web.webServices section.
  • Verified the presence of ScriptModule entry in the System.webServer.modules section as per documentation.

However, when viewing the HTML page in a browser, the following issues arise:

  • The web request goes through, but the results show unprocessed HTML from the ASPX page.
  • The GetAllContacts method remains uninvoked despite setting a breakpoint in the code.
  • The code to call the Web service executes, and the JavaScript callback function upon request completion works correctly.

It seems like the JavaScript setup is correct, but for some unknown reason, the HTML page doesn't execute the WebMethod on the ASPX page, behaving as if it's a regular HTML GET request. This poses a challenge since a JavaScript eval cannot evaluate an HTML document, adding to the confusion. (Also, the JSON data is missing from the returned HTML.)

Currently baffled by this issue. I've scoured countless Microsoft articles, StackOverflow posts, and CodeProject resources. The code seems fine superficially, but I know there's a simple, obvious mistake I'm overlooking. Seeking guidance to identify and rectify it.

Below, you'll find snippets of the ASPX page and the HTML code, in hopes of shedding light on the problem.

ASPX Code


    // ASPX code snippet here

HTML Code


    // HTML code snippet here

Development Environment Details

  • Vista Ultimate SP 2
  • Visual Studio 2008
  • .NET Framework 3.5
  • Solution running on the "local Web server" provided by Visual Studio, not deployed yet.
  • Both ASPX page and HTML page are within the same solution.

Answer №1

It seems that calling the web method with a POST request is necessary. Consider modifying this part of the code:

xmlhttp.open("POST", "/Q2.aspx/GetAllContacts", true);
xmlhttp.setRequestHeader("content-type", "application/json");
xmlhttp.setRequestHeader("Accept", "application/json");
xmlhttp.onreadystatechange = function () 
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
    {
            var jsonResultBuffer = JSON.parse(xmlhttp.responseText);
            objectData = jsonResultBuffer.d;
            DisplayTable();
    }
};

The response is returned in JSON format with "d" as the key in xmlhttp.responseText

Answer №2

Could you please attempt the following using jQuery to check if the web service is accessible?

$.ajax({
        type: "POST",
        url: "Q2.aspx/GetAllContacts",
        data: "",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
           alert("Request successful");
        },
        error: function(response, aa) {
            alert("Request failed");
        }
    });

Thurein

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with the addEventListener function not working on a vanilla JS form?

I'm struggling to get a form working on a simple rails project. The idea is to collect a name and date from the form and display them on the same page using JS. Later, I'll process this information to determine if it's your birthday and cal ...

Divide a JavaScript project into multiple packages using either webpack or npm

I am embarking on the development of an application that needs to be compatible with Windows (PC), Android, and iOS. To achieve this, I plan to use Electron for Windows and React Native for mobile platforms. Both applications will be built using React and ...

When a jQuery click event is triggered, the event.target will return the child element that was clicked within the

When I have a jQuery click event assigned to a hyperlink that contains an image, each with separate ids, I expect clicking the hyperlink to trigger the code event.target.id, returning the hyperlink's id. However, it actually returns the image's i ...

Which of the two async functions will be executed first?

const [counter, setCounter] = useState(0) Consider the scenario where we have two asynchronous functions, func1 and func2, both of which are responsible for updating the counter state. It is specified that func1 is supposed to execute before func2. async ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

Tips for referencing a string in JavaScript

I am trying to use the showmodal method, but I keep getting an error when passing a string. It works fine with integers, but how can I pass a string in JavaScript? <script> var table = ' <table id="example" class="table table-striped " w ...

Analyzing a server's log data at regular intervals

Currently, I am working on a project where I need to parse a server log file using JavaScript every 24 hours and then store the extracted information in a MongoDB database. The process of parsing the data and storing it is what I find to be the most chall ...

Bootstrap Dropdown Functionality Malfunctioning

Here is a simple piece of HTML code that I have created: <!doctype html> <html> <head> <meta charset="utf-8"> <title>.:Home Page:. The Indian Sentinel</title> <link rel="stylesheet" href=" ...

ERROR: Attempting to reference an object that has not been initialized

I am facing an issue with inserting values from textboxes into an SQL table upon clicking the Submit button. The error message "Object reference not set to an instance of an object" is displayed. Below is the code I have written for this functionality. Any ...

Steps to implement provided information in a post within the header of a webpage

Recently, I started creating websites from scratch and I encountered a problem that I could use some help with. The issue is when I have a YouTube video embedded in a post, but I want to showcase the video in the header section of that specific post URL wi ...

Creating effective test cases for Angular JS controllers

Our team has recently taken on the task of writing test cases for our application, specifically focusing on controllers. Utilizing Mocha, Chai, and Sinon libraries, we are looking for guidance on how to effectively write these test cases. We have shared a ...

Navigating through different sections of your Angular app can be easily accomplished using

My current project structure is set up like this: The application I am working on is hosted in a subdirectory called /my-scripts/vk.plants. This means that when I request this URL, it loads layout.html and returns it to the user. layout.html contains the ...

Is there an efficient method for transferring .env data to HTML without using templating when working with nodejs and expressjs?

How can I securely make an AJAX request in my html page to Node to retrieve process.env without using templating, considering the need for passwords and keys in the future? client-side // source.html $.get( "/env", function( data ) {console.log(data) ...

The onChange function failed to provide the expected target value

I attempted to implement an onChange function for a TextArea component, but I encountered an issue where the state was not updating when using console.log or passing it to the payload. Interestingly, when I used JSON.stringify, the value was successfully ...

I'm having difficulty implementing a vue-awesome icon on my project

I am attempting to utilize the standard window-close icon from vue-awesome. I have imported my vue-awesome using the following code: import 'vue-awesome/icons'; import Icon from 'vue-awesome/components/Icon.vue'; Vue.component('i ...

Preventing Errors in C# Type Conversion: Tips and Tricks

One of my colleagues is working with an object that contains multiple generic list collections, each implementing a specific interface. The goal is to create a single list that combines all the other lists so that the objects can be looped through and thei ...

Can you explain the purpose of the statement `var MyConstructor = function MyConstructor()`?

Can you explain the distinction between these two code snippets: var NodestrapGenerator = module.exports = function NodestrapGenerator() { yeoman.generators.Base.apply(this, arguments); // more code here }; and: var NodestrapGenerator = module.expor ...

Update an element's margin-right value with jQuery

I have designed a basic <ul> list in HTML and applied different margin-right values to each of the <li> elements using CSS (jsFiddle). Here is the HTML code: <ul> <li>First</li> <li>Second</li> <li& ...

Identifying line breaks caused by browsers or CSS forced line breaks

<p style="width:60px"> This is just a sample text. It is a piece of text that doesn't really say anything meaningful.</p> When this text is rendered as HTML, it would look like this: This is just a sample text. It is a piece of text ...

Using Regex in JavaScript to split a string based on a saved pattern

I have a specific sentence to work with: var sentence="example of+a+string"; My goal is to split the string by the + symbol only when it occurs after the word "of". When attempting this with the code: sentence.split(/of(\+)/) The result splits th ...