Utilizing AJAX to Invoke a Method in a CS Page: A Step-By-

I am trying to utilize AJAX to call a method in my CS page. Below is the design code I am using:

<!-- Name -->
<input type="text" name="name" id="name" required="required" class="form" placeholder="Name" />
<!-- Email -->
<input type="email" name="mail" id="mail" required="required" class="form" placeholder="Email" />
<!-- Subject -->
<input type="text" name="subject" id="subject" required="required" class="form" placeholder="Subject" />
<!-- Message -->
<textarea name="message" id="message" class="form textarea" placeholder="Message"></textarea>
<!-- Send Button -->
<button type="button" id="submit" name="submit" class="form-btn semibold">Send Message</button>

Here is the ajax implementation:

$(document).on("click", "#submit", function (e) {
     $.ajax({
         type: "POST",
         url: "OakscrollWebService.cs/SendMail",
         dataType: "json",
         data: JSON.stringify({ name: $('#name').val(), email: $('#mail').val(), subject: $('#subject').val(), message: $('#message').val() }),
         contentType: "application/json; charset=utf-8",
         success: function (data) {
             alert(data.d);
         },
         failure: function (data) {
             alert("something went wrong");
             //console.log(msg);
         }
     });
 });

I have also added an asmx page (web service) with a reference call to the CS file in the App_Code folder. Here is the code:

<%@ WebService Language="C#" CodeBehind="~/App_Code/OakscrollWebService.cs" Class="OakscrollWebService" %>

The CS file contains the method I am trying to call using AJAX. Here is the method code:

[WebMethod]
public static void SendMail(string name, string email, string subject, string message)
{
    // Code for sending email
}

Despite implementing the ajax call, I am facing issues like "403 forbidden" and "500 server not found", preventing me from successfully calling the SendMail method.

Answer №1

Hey there! It seems like updating your URL to include the file extension .asmx instead of .cs might resolve the issue (just change

url: "OakscrollWebService.cs/SendMail",
to
url: "OakscrollWebService.asmx/SendMail",
). I encountered a 404 error when testing, indicating that the page was not found. Consider validating your JSON with a tool like JSONLint.

$(document).on("click", "#submit", function (e) {
      var data = '{"name":"' + $('#name').val() + '", "email":"' + $('#mail').val() + '", "subject":"' + $('#subject').val() + '", "message":"' + $('#message').val() + '"}'; //You may want to validate your JSON
         $.ajax({
             type: "POST",
             url: "OakscrollWebService.asmx/SendMail",
             dataType: "json",
             data: JSON.stringify({ name: $('#name').val(), email: $('#mail').val(), subject: $('#subject').val(), message: $('#message').val() }),
             contentType: "application/json; charset=utf-8",
             success: function (data) {
                 alert(data.d);
             },
             failure: function (data) {
                 alert("something went wrong");
                 //console.log(msg);
             }
         });
     });
  });

Wishing you the best of luck!

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

Retrieve the request body in Node.js Express server-side code in order to receive an array passed from the front end

I am facing an issue where I need to save a user's array to mongo. When the data passes through the bridge and reaches the posts, it appears as a strange object with string versions of its indices. I am attempting to convert it back into a normal arra ...

Express.js fails to redirect to the sign-in page after successfully retrieving the username from the MySQL database

I have encountered an issue while trying to retrieve the username from a MySQL database. The code I am using successfully retrieves the username, but when an error occurs, instead of redirecting to /signin, it redirects to /admin. Adding res.redirect(&ap ...

Display routes in React using the react-router package

Can I use a console command at runtime to display all routes in my application? Despite utilizing react-router, not all routes seem to be functioning properly. In Rails, you can retrieve a list of routes during runtime. ...

Error Type: Property 'history' is not defined and cannot be read

My goal is to automatically redirect the user to the login page when they hit the /logout route. The authentication process works as expected (jwt token is removed), but I'm encountering issues with the app failing to redirect to /login upon logout. ...

Developing a timeline using a JSON file and dynamically altering the page based on the specified datetime within the JSON data

I am currently working on a project that involves a JSON file containing information about missions. This JSON file is subject to continuous updates and has a specific structure as shown below: [ { "module_id": 5, "title": "TITLE 1", "media ...

Utilizing JavaScript to assign object properties (column names) from an Array of Objects to a specific row and column header

I am currently in the process of implementing a mapping function to display data from an array of objects, initially stored in localStorage, into a table using Material-UI Table. The goal is to map all the specific column names into corresponding Table Ce ...

The transition from material-ui v3 to v4 results in a redux form Field component error stating 'invalid prop component.'

Since upgrading from material-ui v3 to v4, I am encountering an error with all my <Field> components that have the component prop. Error: Warning: Failed prop type: Invalid prop component supplied to Field. The Field component is imported from im ...

Is there a way to stop window.pageYOffset from resetting every time the page is rendered?

I've been working on a react component that changes the header based on the scroll event. By attaching an event handler and toggling a display class to show or hide certain elements depending on the scroll position. However, I've encountered som ...

Strategies for concealing and revealing content within dynamically loaded AJAX data

I am attempting to show and hide data that is loaded using Ajax. $.ajax({ type: "POST", url: "/swip.php", data: {pid:sldnxtpst,sldnu:sldnu}, success: function(result) { $('.swip').prepend(result); } }); This data gets ...

Steps for executing a Node script are as follows:

My task is to execute a node script that will remove an object from an external API. This can be achieved by running the following command: node server.js Customer55555 Upon execution, the specified object should be deleted successfully. To interact wit ...

Is there a way to eliminate curly braces from JSON strings with a regular expression?

Hello, I am working with a JSON file and I need to manipulate the content of the chapters array. Specifically, I want to remove the curly braces from inside the strings but only if they contain more than three words (two spaces). Is it achievable using Reg ...

Tips for retrieving a value returned by a Google Maps Geocoder

geocoder.geocode( { 'address': full_address}, function(results, status) { lat = results[0].geometry.location.lat(); lng = results[0].geometry.location.lng(); alert(lat); // displays the latitude value correctly }); alert(lat); // does ...

Angular Transclude - ng-repeat fails to iterate over elements

Recently, I've been experimenting with Angular directives and encountered a peculiar issue... Check out the code snippet below: <!DOCTYPE html> <html> <head> <title>Directive test</title> <script type="text/ja ...

Incorporate jQuery to add numbering to rows along with input fields

I am trying to implement automatic numbering on the first column. Is there a way to increment the number by 1 every time the Submit button is pressed? jQuery: $(document).ready(function () { $("#btn-add").click(function () { va ...

Trouble with displaying canvas images in imageDraw() function

I'm having trouble with my Imagedraw() method when trying to obtain image data using toDataURL(). var video = document.getElementById('media-video'); var videoCurrentTime = document.getElementById('media-video').currentTime; var ...

Initially, when fetching data in React, it may return as 'undefined'

I have a function component in React that handles user login. The functionality is such that, based on the username and password entered by the user in the input fields, if the API response is true, it redirects to another page; otherwise, it remains on th ...

Pinpointing a specific region within an image by utilizing offsets

Would it be possible to detect a specific area within an image using a predefined set of image offsets? Here is the image and accompanying offsets: Sample Image Below are the sample image offsets for the highlighted area: Offset(63.4, 195.2) Offset(97.7 ...

the value of properrty becomes undefined upon loading

In my code, there exists an abstract class named DynamicGridClass, containing an optional property called showGlobalActions?: boolean?. This class serves as the blueprint for another component called MatDynamicGridComponent, which is a child component. Ins ...

Is there any importance to port 9229 and is it possible to modify it?

In my initial training, it was always recommended to run a local Node server on port 3000. However, after learning about the Chrome Node debugger in a tutorial that uses port 9229, I decided to switch to this port. For more information on port 3000, you ...

How to open a hyperlink in a separate background tab with JavaScript or jQuery

I am in need of a feature that automatically opens all links on a website in a new background tab when a user clicks on them. Despite searching extensively, I have not found a solution that works across all browsers. To implement this, I have referred to t ...