Encountering a 500 server error when making an Ajax call to a SOAP web method in the .Net framework

Having trouble with two different async calls using ajax. Both are done the same way, but one has parameters for the web method. The link is correct, as I get the return correctly in the browser when I follow it, but I keep getting a server 500 error. Any ideas? The call works fine without parameters. Here's the JS/jQuery code:

function CatChanged() {
    var strA = $('#ddlCategory').val();
    $.ajax({
        url: encodeURI('https://localhost:44380/WebService1.asmx/GetProducts?category=' + strA),
        data: '<soap: Envelope xmlns: xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd="http://www.w3.org/2001/XMLSchema" xmlns: soap="http://schemas.xmlsoap.org/soap/envelope/%22%3E<soap: Body><xmlns="http://tempuri.org/" /></soap: Body></soap: Envelope >',
        type: 'POST',
        contentType: "text/xml",
        dataType: "text/xml",
        success: function (response) {
           alert(response.responseText);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("ERROR!!");
            alert(xhr.status);
            alert(thrownError);
        }
    });
}

Here's the web method code from the C# code behind:

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string GetCategories()
        {
            Catalog cat = new Catalog();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(cat.categories);
        }

        [WebMethod]
        public string GetProducts(string category)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            Catalog cat = new Catalog();
            List<string> retList = new List<string>();
            switch (category)
            {
                case "Electronics":
                    foreach (Product product in cat.electronicProducts)
                    {
                        retList.Add(product.itemName);
                    }
                    return jss.Serialize(retList);
                case "Apparel":
                    foreach (Product product in cat.apparelProducts)
                    {
                        retList.Add(product.itemName);
                    }
                    return jss.Serialize(retList);
                case "Food and Drink":
                    foreach (Product product in cat.electronicProducts)
                    {
                        retList.Add(product.itemName);
                    }
                    return jss.Serialize(retList);
                default:
                    foreach (Product product in cat.electronicProducts)
                    {
                        retList.Add(product.itemName);
                    }
                    return jss.Serialize(retList);
            }
        }

... Screenshot of the return in the browser when following the direct link from the developer's console in Chrome: https://i.sstatic.net/gFmYb.png

The return is good from the web method when called from the URL, indicating an issue with the ajax call. Need to figure out what needs to be changed to consume the parameter in the web method. First web method works, able to parse everything from the return just fine.

Using any other services, MVC, or similar options isn't possible. Need to make it work given the current limitations.

Answer №1

Okay, so let me make sure I understand your issue correctly. It seems like when you access the URL directly in your browser, everything works as expected. However, when you make an AJAX call, you encounter some difficulties.

One thing that stood out to me in your code is that you are sending a POST request in your AJAX call, but the methods specified are both GET. I recommend changing the type in your AJAX call to GET instead.

For example:

function CatChanged() {
    var strA = $('#ddlCategory').val();
    $.ajax({
        url: encodeURI('https://localhost:44380/WebService1.asmx/GetProducts?category=' + strA),
        data: '<soap: Envelope xmlns: xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd="http://www.w3.org/2001/XMLSchema" xmlns: soap="http://schemas.xmlsoap.org/soap/envelope/%22%3E<soap: Body><xmlns="http://tempuri.org/" /></soap: Body></soap: Envelope >',
        type: 'GET', // <-- Changed from POST to GET
        contentType: "text/xml",
        dataType: "text/xml",
        success: function (response) {
           alert(response.responseText);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("ERROR!!");
            alert(xhr.status);
            alert(thrownError);
        }
    });
}

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

"How can we trigger a re-render of a React component once a promise is fulfilled? Is there a way to prevent rendering until the

Having attempted to make updates to a functional component that interfaces with an azure-devops-ui/Filter, I've encountered a situation where I am utilizing the azure-devops-extension-sdk to handle async responses. This component is intended to be use ...

Obtain Data Grid from Website

I need to extract a table with the following columns: "Date|Open|High|Low|Close|No.of Shares|No.of trades|Total Turnover|Deliverable Qty" from the website "" Below is the code I am using: Sub Macro_BSE() Application.ScreenUpdating = False Dim File ...

Is there a way to customize a package.json file using postinstall?

I've developed a package on npm that generates an "scss directory structure" and my goal is to include custom scripts in the package.json file located at the project's root. MY-PROJECT ├── node_modules ├── scss └── package.json ...

"Stay current with real-time updates in seconds using React technology

Check out this code snippet: const currentTime = new Date().getTime(); const targetTime = new Date('November 15, 2020').getTime(); const difference = currentTime - targetTime; let seconds = Math.floor(difference / 1000) % 60; setInterval(functio ...

"Utilizing Promises in AngularJS Factories for Synchronous API Calls

Attempting to implement synchronous calls using a factory pattern. $scope.doLogin = function (username, password, rememberme) { appKeyService.makeCall().then(function (data) { // data = JSON.stringify(data); debugAlert("logi ...

Switching the children image source by hovering over the parent element

I have a React component that functions as a card containing a title and an image. I want the image to change upon hovering over the entire card, rather than just the img element itself. While CSS and the background property could achieve this, I prefer k ...

Client-side validation with JQuery for a custom attribute

I recently developed a unique Custom Validation Attribute: public sealed class DateValidatorAttribute : DataTypeAttribute { /// <summary> /// Constructor for the DateValidator Attribute. /// </summary> publi ...

Transform Vue.js into static HTML output

Is there a way to convert a Vue.js component into static html without the need for javascript? I am specifically interested in retaining styles. I am searching for a library where I can execute code similar to this: SomeNestedComponent.vue <template> ...

Why does my Node.js script seem to be running synchronously instead of asynchronously?

Currently working on a Node.js exercise from Nodeschool.io. The task is as follows: # LEARN YOU THE NODE.JS FOR MUCH WIN! ## JUGGLING ASYNC (Exercise 9 of 13) This problem is the same as the previous problem (HTTP COLLECT) in that you need t ...

Generate clickable links on a web page with PHP and a form

Every week I find myself tediously creating links by manually copying and pasting. It's starting to feel like a crazy process, and I'm sure there must be a faster way. A123456 B34567 d928333 s121233 I need these numbers to be transformed into h ...

Enable only the current week days on the multiple date picker feature

Can anyone recommend a date picker that only shows the current week and allows for multiple date selections by the user? I found this jsfiddle which limits the display to the current week, but it doesn't support selecting multiple dates. I attempted ...

Instagram API: Retrieving a list of recently tagged media only displays content that belongs to me

Is there a way to retrieve all recently tagged media from all users, similar to what is shown on this link ? The Instagram API only provides media from the access_token's owner. Once again: requestUrl = 'https://api.instagram.com/v1/tags/&apo ...

Insert within a canvas

Although there is a previous inquiry on this topic, it appears to be outdated. Despite searching through dartlang's resources and conducting online research, I have yet to find a solution to the issue at hand. document.onPaste.listen((e) { ...

Developing Angular dynamic components recursively can enhance the flexibility and inter

My goal is to construct a flexible component based on a Config. This component will parse the config recursively and generate the necessary components. However, an issue arises where the ngAfterViewInit() method is only being called twice. @Component({ ...

Issue with slideout menu hyperlinks malfunctioning

Currently developing a site at , everything seemed ready for deployment until testing in 320x480 mode on mobile revealed that the links on the slideout menu were not working on any mobile device I tried, regardless of resolution or page. I've tried u ...

Using PHP to pass variables to an external JavaScript file

I have come across the following code snippet: PHP <?php include("db.php"); ?> <html> <head> <title>Title</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/j ...

Explain the operation of recursive function calls in JavaScript

I’ve been working on converting the algorithm found in this Python code snippet into JavaScript. function divide(arr, depth, m) { if (complements.length <= depth) { complements.push(2 ** (depth + 2) + 1); } var complement = comple ...

Is it possible to modify the color of a division row using an onchange event in JQuery?

I am facing a requirement to dynamically change the color of rows based on the dropdown onchange value. The rows are structured in divisions, which were previously tables. There are two main divisions with rows that need to be updated based on dropdown sel ...

Adding the <a> tag causes Superfish to malfunction

I've been struggling to get the latest Superfish menu code working with lists that include the <a> tag. I've double-checked everything, but it seems like I'm missing something obvious. Can anyone help me figure out what's wrong? ...

The setting `ensureCleanSession: true` doesn't appear to be effective when included in the capabilities for Internet Explorer 11

Currently, I am testing a login/logout application with the help of protractor. One challenge I am facing is dealing with a popup that appears after each login/logout scenario. In order to ensure the popup appears after each login, I need to reset the IE ...