What could be causing my ajax request to not connect to my .NET WebMethod?

Can someone please assist me with figuring out why this code is not functioning properly? I would greatly appreciate a second pair of eyes to take a look - Thanks in advance!

This function seems to be successful, but the C# method is not being triggered.

JavaScript

$(function() {
    ($("#survey").on("submit", function() {
        var data = serializeForm();
        $.ajax({
            type: "POST",
            url: "Default.aspx/SaveSurveyInfo",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                alert('ok');
            },
            error: function(data) {
                alert('failed');
            }
        }); //ajax

        return false;
    }));

    function serializeForm() {

        var data = new Object;

        $("#survey input[type='checkbox']").each(

        function(index) {
            data[$(this).get(0).id] = $(this).get(0).checked ? 1 : 0;
        });
        data.otherEnviron = $("#survey input[type='text']").val();
        var strData = JSON.stringify(data);
        return strData;
    }
});

Updated Code:

    $(function () {
        ($("#survey").on("submit", function() {
            var data = serializeForm();
            alert(data);
            $.ajax({
                type: "POST",
                url: "Default.aspx/SaveSurveyInfo",
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    alert('ok-'+ data);
                },
                error: function (xml, textStatus, errorThrown) {
                    alert(xml.status + "||" + xml.responseText);
                }
            }); //ajax

            return false;
        }));

Note:

strData="{\"ms\":1,\"google\":0,\"PHP\":0,\"otherEnviron\":\".NET\"}"

C# WebMethod

[WebMethod]
private void SaveSurveyInfo(int ms, int google, int PHP, string otherEnviron)
{
    using (SqlConnection scon = new SqlConnection(connectionString))
    {
        scon.Open();
        SqlCommand scmd = scon.CreateCommand();
        scmd.CommandType = System.Data.CommandType.StoredProcedure;
        scmd.CommandText = "SurveyResults";
        scmd.Parameters.AddWithValue("MicrosoftTranslator", ms);
        scmd.Parameters.AddWithValue("GoogleTranslator", google);
        scmd.Parameters.AddWithValue("PHPOkay", PHP);
        scmd.Parameters.AddWithValue("other", otherEnviron);
        scmd.ExecuteNonQuery();
    }
}

Revised C# Code:

[WebMethod]
public static void SaveSurveyInfo(int ms, int google, int PHP, string otherEnviron)
{
    try
    {
        using (SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["C287577_NorthwindConnectionString"].ConnectionString))
        {
            scon.Open();
            SqlCommand scmd = scon.CreateCommand();
            scmd.CommandType = System.Data.CommandType.StoredProcedure;
            scmd.CommandText = "SurveyResults";
            scmd.Parameters.AddWithValue("MicrosoftTranslator", ms);
            scmd.Parameters.AddWithValue("GoogleTranslator", google);
            scmd.Parameters.AddWithValue("PHPOkay", PHP);
            scmd.Parameters.AddWithValue("other", otherEnviron);
            scmd.ExecuteNonQuery();
            scmd.Dispose();
        }

    } catch(Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

The issue still persists as there are no error messages shown, only 'ok'.

Answer №1

WebMethod should always be marked as public and static.

You may find a related question here: ASP.NET jQuery issue: Web Method Not Recognized

To enhance the security of your ajax calls, consider transferring them to a web service.

Answer №2

protected static void StoreSurveyData

To ensure accessibility on aspx pages, this method must be declared as both static and public.

In the case of asmx pages, it is sufficient for the method to be designated as public only.

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

Arrows on the button are unresponsive and there seems to be an incorrect number of

I've been working on a project by combining various examples I found online. I'm puzzled as to why it's displaying all the buttons at once instead of just one per page, and why the number of visible buttons decreases by one with each right c ...

Position the caret after adding a new element in a content-editable div

I have a contenteditable div that contains various elements. My goal is to automatically create a new paragraph tag right after the element where the cursor is positioned when the user presses the enter key. Currently, I am able to insert the paragraph tag ...

What is the method to modify the hover background color and click background color for a dropdown item using Bootstrap Vue?

Hovering over the dropdown will change its background color to a light gray. The code below shows the dropdown in a navbar. <b-nav-item-dropdown text="TOOLS" right> <b-dropdown-item href="#" class="dropdown-mine">1</b-dropdown-item> ...

No data found in req.query object in ExpressJS

When I use http.post to send data from Angular to NodeJS, the req.query always comes back empty for me. Here is my server.js setup: const express = require('express'); const cors = require('cors'); const bodyParser = require('body ...

Variation in Map Behavior in d3 Due to Datum-Data Discrepancy

I'm relatively new to utilizing d3js and I am endeavoring to grasp the distinction between employing data and datum for associating data with elements. Despite having spent quite some time reading various materials online, I still lack an instinctive ...

How can I display a div within a parent container in Angular 2?

Instead of pasting my loading modal pop-up to every page in the app, I want it to appear at the parent component (i.e. "app.component.ts"). This way, I can easily call it multiple times throughout the application. Now, I have pages with different routes t ...

A more detailed explanation of Angular's dot notation

I came across a solution for polling data using AngularJS here on stackoverflow. In this particular solution (shown below), a javascript object is used to return the response (data.response). I tried replacing the data object with a simple javascript arra ...

The middleware is causing disruptions in the configuration of redis and express

I've recently started using Redis and I'm facing an issue with my middleware 'cache' function that seems to be causing problems in my code. Everything works fine without it, the data displays correctly in the browser, and when I check f ...

The redirection to the webpage is not occurring as expected

I've been attempting to redirect another webpage from the homepage in my node server. However, the redirect isn't working as intended to link to idea.html, where the relevant HTML file is located. Can anyone assist me in identifying any errors in ...

Using JSON format to pass variables in C# programming language

Is there a way to properly pass my variable within a JSON string like this? string name = "john"; string json = @"{ 'EmployeeName': name, 'EmployeeID': '123', } I ke ...

Incorporating intricate HTML elements through a Chrome content script

Currently, I am utilizing Chrome extension's content script to generate a sophisticated display that is incorporated into web pages. Initially, I tested it by integrating it directly onto a website, but now I want to package it in an extension. The ...

Disable onclick action for programmatically created buttons

I'm facing an issue with the code I'm using to delete messages on my website. The problem is that while newly added messages are being dynamically loaded, the delete button (which links to a message deletion function) does not seem to be working. ...

Leveraging Jquery Splice

Trying to eliminate an element from an array using the Splice method. arrayFinalChartData =[{"id":"rootDiv","Project":"My Project","parentid":"origin"},{"1":"2","id":"e21c586d-654f-4308-8636-103e19c4d0bb","parentid":"rootDiv"},{"3":"4","id":"deca843f-9a72 ...

Display the div only during the printing process

Imagine I have a situation where there is a block of content that I only want to show when printing. It looks something like this: <div id="printOnly"> <b>Title</b> <p> Printing content </p> </div&g ...

Alternative to Lodash for performing a check operation in JavaScript and assigning a new value

Recently, I've been utilizing a code snippet to verify the value of an input field located at index:1 within an array. The code looks like this: const inputValue=journeyData && journeyData.birthdate && journeyData.birthdate[0] ...

Getting data from components in React: A step-by-step guide

As a newcomer to Reactjs, I find myself working on an existing project where I am attempting to retrieve product reviews using components. However, my console currently displays 0 reviews. How can I resolve this issue? The file in question is "pages/[slug ...

Preserve selected value in dropdown menu post form submission

Is there a way to have the selected option displayed on a drop-down list after form submission instead of always showing the first option? <form id="myform" > <label for="selectoption">Departments</label> ...

What steps do I need to take to ensure NextJS stores my edits in VSCode?

I have attempted various troubleshooting steps such as changing file extensions from .js to .jsx, turning on Prettier for formatting upon saving, setting it as the default formatter, reloading and restarting the editor. However, the issue with not being ...

A guide on iterating through a JSON object in Vue and Javascript to retrieve keys and values, checking if they are either distinct or null

Looking for a way to iterate through a JSON object that may or may not have properties fields, which can be null or contain various configurations. I need to display it in a code block. Below is the example JSON data: "grade": [ { ...

Is it possible to change the button class within a div while ensuring only the last one retains the change?

Here is a code snippet I'm using to switch between classes for buttons: $('button').on('click', function(){ var btn=$(this); if(btn.attr('class')=='tct-button'){ btn.removeClass('tct-button ...