c# server-side method is failing to execute when called from an AJAX request in ASP.NET

I am attempting to utilize ajax to call a C# method in the following manner.

<a href="#divrecentQ" id="linkdivrecentQ" onclick="lnkClick();" aria-controls="divrecentQ" role="tab" data-toggle="tab">Click here</a>

Below is the corresponding JavaScript method:

    function lnkClick() {
        alert("called");
        $.ajax({
            type: "POST",
            url: '/amain.aspx/LoadImages',
            data: {},
            success: function () {
                alert(1);
            },
            dataType: 'html'
        });
        alert("cal");
    }

On the server side:

    public static void LoadImages()
    {
       
        log.Debug("LoadImages is called");
       
    }

Unfortunately, the server side method is not being executed.

Any assistance would be greatly appreciated.

Thank you

Answer №1

To properly set up the method as static and expose it as a web method, ensure that you define it as such and wrap it with the [WebMethod] attribute.

[WebMethod]
public static void LoadImages()
{
    Label1.Text = "hello world";
    Response.Redirect("www.yahoo.com");
    log.Debug("LoadImages method has been invoked");
}

Answer №2

By including the line "contentType: "application/json; charset=utf-8"," in JQuery, the server side method was successfully invoked.

Grateful for everyone's assistance. :)

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

Create a smooth transition: How to make a hidden button appear after a function finishes in JavaScript

I am completely new to the world of JavaScript, HTML, and CSS, so I'm feeling a bit lost on how to proceed with this task. My goal is to create a script that will initially display some text through a specific function. Once that text has been displa ...

Even in the face of errors, Selenium with Node.js continues to run seamlessly. The challenge arises specifically with the 107.xx version of the Chrome browser and Chrome driver

Currently, I am employed in a project involving NODE JS (javascript) with selenium webdriver. Package.json- “chai”: “^4.3.6”, “chromedriver”: “^107.0.3”, “geckodriver”: “^3.2.0”, “mocha”: “^10.0.0”, “mochawesome”: “^7. ...

Securing Ajax Post Requests

Currently, I am working on creating a mobile application using PhoneGap that will interact with a server (PHP) through ajax requests. Regarding the PHP server side, an example link like https://example.com/retrieveData.php will receive the user id via $_P ...

Ensure the button remains in focus after clicking on the input field: Material-Ui

I'm currently working with a material-ui dialog and I've encountered an issue. When I click on the input field, the social button loses focus which is not what I want. Here's how it looks: https://i.sstatic.net/vNRrP.png Here's the de ...

Transferring API information into a nested array and displaying the outcome

Currently, I am utilizing an API to fetch an array of users from which I sort them and collect those with a personalTrainerId matching my userId into an array. The ultimate goal is to render these users as cards on the interface. The desired format for th ...

Disabling the loading of JavaScript on a Magento website

Seeking advice - I'm experiencing a delay on my website due to 3 unnecessary javascripts that are being loaded. Is there a way to prevent these scripts from loading or being searched for? Listed below is the website log where I am unable to locate jq ...

Troubleshooting a problem with selecting options in Jquery

Looking for assistance with a jquery script. I have a select dropdown that fetches a list of options via Ajax. When a user clicks on an option, if a certain variable equals 1, an HTML div is added. If the variable changes to another value, the HTML div dis ...

Is there a way to transfer the jQuery code I've developed on jsfiddle to my website?

I am currently developing a website for fun, using HTML and CSS. While I have some familiarity with these languages, I have never worked with jQuery before. However, for one specific page on the site, I wanted to incorporate "linked sliders," which I disco ...

Ensure that the three.js script remains in a fixed position on a page that can be

Is there a way to make a 3D model created with three.js have a fixed position on a scrollable page, like a background while the rest of the content scrolls normally? Are there any CSS techniques or additional script elements that can be used to achieve thi ...

Dynamically updating fields in PHP using jQuery's passed variable

In my web application, I have a selection of locker numbers available in a dropdown list that is populated from MYSQL/PHP. My goal is to display each locker's combination and location when a user selects a locker number from the dropdown list on the s ...

Retrieving values of child elements from JSON using C#

public static void apiCall2() { WebClient c = new WebClient(); var data = c.DownloadString(baseURL + endPoint + "?access_key=" + accessKey + "&currencies=TWD&source=USD&format=1"); //Console.WriteLine(data); JObject api = JObjec ...

The Jquery delete button is efficiently targeting and removing all image sources and identifiers within a Multiple Upload feature

I need help creating a delete button for my ImageUploader. I can successfully select an image and display it in a div on my page, but deleting the current image is proving to be challenging. When I click on the delete button, instead of getting the id and ...

Display the chosen option's value with PHP - Nothing Else

I am new to PHP and encountering an issue with my project. I have created a database that contains a "members" table with columns for "member_id" and "member_name". I've also set up a select box populated with members' names. My goal is to echo t ...

AJAX for displaying a partial view or handling form validation errors

Struggling with implementing AJAX form processing in Rails? Let me break down my code and share my uncertainties: This is the snippet from my new.html.erb: <%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_na ...

Creating a custom HttpClientHandler for a specific named HttpClient by utilizing the HttpClientFactory

Original Code: Client = new HttpClient(new HttpClientHandler() { DefaultProxyCredentials = CredentialCache.DefaultNetworkCredentials }); // set a default user agent string, some services do not allow empty user agents if (!Client.DefaultRequestHeaders.Co ...

The split function in JavaScript is exhibiting some unusual behavior

There is something wrong with my code challenge1 = () => { var data = fs.readFileSync('santa21.txt', 'utf8'); data = data.toString(); dataSplit = data.split(' ') console.log(dataSplit); }; challenge1(); The result of the ...

Angular (2/4) application utilizing custom-named routing within a single page architecture

I'm currently working on an Angular application that consists of a login component and a home component which serves as the main handler for the entire single page application. Additionally, I have three more components named users, each with function ...

Saving an item using localStorage

I've been struggling to figure out how to make localStorage save the clicks variable even after refreshing the browser. Initially, I attempted using JSON.stringify and JSON.parse but later discovered that using parseInt could be a more suitable optio ...

Validation of Button Groups and Automatic Disabling after Initial Click with HTML, CSS, and JavaScript

Criteria: Upon clicking a button from the selection of four buttons, all other buttons should become disabled except for the Next button. An alert window must appear when the Next button is clicked without selecting any other buttons, preventing navigatio ...

Unable to assign a value to the HTMLInputElement's property: The input field can only be set to a filename or an empty string programmatically

When attempting to upload an image, I encountered the error message listed in the question title: This is my template <input type="file" formControlName="avatar" accept=".jpg, .jpeg .svg" #fileInput (change)="uploa ...