Having trouble transferring data from an aspx file to the code behind using $.ajax({ type: "POST", with Visual Studio 2017 C#?

Utilizing web-forms to gather data from a form and then transmit the data to the code-behind in order to forward it to an API. By clicking on a button, I trigger a JavaScript function that gathers the data and then sends it over to my aspx.cs file for communication with the API. The HTML code snippet for the button is as follows:

<button class="search btn" ID="btnSearch" onclick="searchApi(); return false;"><i class="fas fa-search"></i>Search</button>

This executes the searchAPI() function which successfully creates a concatenated string named SearchData. The corresponding Javascript code appears like this:

var searchString = JsonData;
var trimsearchString = searchString.replace(/,/g, '');

$.ajax({
   type: "POST",
   url: 'Default.aspx/GetApi',
      data: searchString,
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (data) {
          alert('success');
                },
                error: function (errordata) {
                    console.log(errordata);
                    alert(errordata);
                }
    });

The method GetAPI within my Default.aspx.cs script remains untriggered. Here's what the method looks like:

[System.Web.Services.WebMethod]
public static void GetApi(string searchData)    
{...

While the success: function (data) signifies success, the associated code-behind method fails to execute. Any insights on what could potentially be missing would be greatly appreciated.

Answer №1

update the ajax data because it seems like the method with this parameter cannot be found

$.ajax({
   type: "POST",
   url: 'Default.aspx/GetApi',

      data: { searchData: trimsearchString},
      //if the problem persists, you can also try
       data: JSON.stringify( { searchData: trimsearchString}),

      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (data) {
          alert(data);
                },
                error: function (errordata) {
                    console.log(errordata);
                    alert(errordata);
                }
    });

make sure your webmethod returns a value

[WebMethod]
public static string GetApi(string searchData)    
{
   return searchData
}

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

Discover if every single image contains a specific class

HTML : <div class="regform"><input id="username" type="text" name="username" placeholder="Username" required><h3 class="check"><img src=''/></h3></div> <div class="regform"><input id="password" type=" ...

Uploading my application on multiple servers after making changes using AngularJS and PHP

Currently, I am working on an angular-php web application that is live online for multiple users, each on their own subdomain. These subdomains include: sub1.mydomain.com sub2.mydomain.com sub3.mydomain.com sub4.mydomain.com sub5.mydomain.com Issue: An ...

When attempting to submit a record at http://localhost:5173/, a 404 (Not Found) error was

Currently, I am attempting to retrieve username data and timeTaken from a form. My goal is to send this data to my server, create the User object, and store it in MongoDB Atlas. Unfortunately, I am encountering a 404 error that I am struggling to resolve. ...

Interactive searching with Smalltalk Seaside and jQuery as you type

renderFilterOn: html |aFilter| html textInput onKeyUp: (html jQuery ajax callback: [:val | aFilter := val] value: ((html jQuery this) value); script: [:s | s add: ((s jQuery class: 'itemnames') ...

Activate lighting in Three.js with a simple click

I successfully loaded a sphere mesh with Lambert material. Now, I am trying to add a light source to the point where there is an intersection after clicking. target = object that was clicked. to = vector3 of my click. When the dblclick event listener is ...

Guide to setting up a dropdown menu with Material UI in React JS

I'm currently working on a dropdown menu that includes a nested menu structure, as depicted below: https://i.sstatic.net/FleC5.png Upon expanding the dropdown, two options are displayed: https://i.sstatic.net/jQlwN.png The issue I'm facing is ...

Automatically integrating Nivo Lightbox into your website

I incorporated Nivo Lightbox into my website, seamlessly integrating all images with the plugin using the following code: <div class="portfolio-item"> <div class="portfolio-thumb "> <a class="lightbox" data-lightbox-type="ajax" title="Strat ...

JavaScript is displaying Not a Number (NaN) instead of the expected value

Currently, I am facing an issue with retrieving the user's work duration from a database column stored in minutes. My goal is to convert this value to HH:mm format to calculate the total hours worked per week, but I'm encountering obstacles. < ...

Interactive Highcharts tooltip experiencing intermittent glitches during dragging

I am working with two sets of data in a line chart using Highcharts. I am trying to customize the tooltip formatter, but whenever I drag a point, the tooltip starts glitching and flickering on and off repeatedly. For reference, here is the JSFiddle link: ...

Incorporate a genre twist in animated films

Is there a way to implement an animated feature where the letters appear one by one in between a sentence, similar to what is seen on this page? On the linked page, there is a sentence displayed inside a banner that reads: Create meaningful documents Cr ...

Refreshing a series of forms in Javascript

One of the features on my website is a comment section where users can reply to comments. Each comment has a reply form and I am fetching comments from the database using a loop. @foreach($responses as $response) <form action="{{action('Discussio ...

Display content exclusively in PDF format

On my HTML page, I have two sections - one for inputting values and the other for viewing a PDF. To ensure that the PDF view is hidden until explicitly requested, I need it to remain invisible by default. It should only appear as a PDF when someone clicks ...

Inject a value sent from response.render directly into the script tag

Below you will find a pug snippet. I am looking for a way to dynamically insert the user value into the chatConfig object. script. var chatConfig = { user : 'foo', pass : 'bar', } When rendering from my Express applicatio ...

An AJAX function nested within another AJAX function

Is there a way for me to return the second ajax call as the result of the ajax function? I could use some assistance with this. function ajax(url: string, method:string, data:any = null) { var _this = this; return this.csrfWithoutDone().done(funct ...

The issue of height and width always being zero in Chrome when using Classic ASP with JavaScript

Within my markup, I have an image field that I am setting the source for using JavaScript. I am in need of its height and width, so I utilized the image.height() and image.width() methods. Despite working properly in Internet Explorer, these methods do not ...

Steps to eliminate the select all checkbox from mui data grid header

Is there a way to remove the Select All checkbox that appears at the top of the checkbox data column in my table? checkboxSelection The checkboxSelection feature adds checkboxes for every row, including the Select All checkbox in the header. How can I ...

Struggling to click on a dynamic link before it times out

Can someone help me with a puzzling issue I can't seem to solve? I am trying to achieve the following: Whenever a link is clicked (for example: mysite.com/blog/blog-article.html), I want to save the href of that link to a variable. Then, in JavaScri ...

Validation is not being executed by the Form Validator with ajax() call

Utilizing the form validator and an ajax(); call, I am filling in an overlay that will only be displayed after confirming if an email exists in our database. The PHP file will determine whether to show the registration or login forms. My issue currently i ...

Is the error in the Ajax post visible to you?

I'm in the process of trying to make a basic Ajax post function properly. When I send the headers and data to the URL using Fiddler, it comes back with an 'Ok' response. However, when I run the same code in my ajax code, it triggers the erro ...

Is there a way to incorporate my JavaScript code into my page.jsx file efficiently?

Can I integrate this javascript code from a .js file into my .jsx file seamlessly? const { exportTraceState } = require("next/dist/trace"); const toggleBtn = document.querySelector('.toggle_btn') const toggleBtnIcon = document.querySe ...