Sending Javascript values to a WebMethod

I am attempting to pass JavaScript values into my codebehind for processing, encountering various errors as I try different approaches. I am trying to send a Number and Message to the WebMethod.

JS:

function SendMessage() {
var number = document.getElementById("number").value;
var message = document.getElementById("message").value;

var msg = {
    "Number": number,
    "Message": message
};

$.ajax({
    type: "POST",
    url: "Default.aspx/SendMessage",
    data: JSON.stringify(msg),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        alert("Message sent");
    },
    error: function (msg) {
        alert("Message call failed");
    }
});
}

In the codebehind, I have defined a WebMethod and a Message class to store my message

[WebMethod]
public static void SendMessage(string message)
{
    //Create a  TMessage and deserialize to it

}

Message:

public class TMessage
{
    public string Number { get; set; }
    public string Message { get; set; }
}

I expected to receive JSON and deserialize it to a Message type, but my breakpoint in the SendMessage method is not hit. The error message says:

Message=Invalid web service call, missing value for parameter: 'message'.

After some experimentation, changing the parameter from string to object allowed the breakpoint to be hit (with changes to the data: value in the Ajax call). However, it appeared that I was receiving a Dictionary instead of being able to cast it to TMessage.

Any suggestions are appreciated.

Answer №1

When examining webmethod closely, you will notice that it only has one parameter which is message.

In order to make an ajax call, you must pass this parameter like so -

var params = "{'message':'" + message  + "'}";

If you need further guidance, check out this helpful link - Send JSON to webmethod?

function SendMessage() {

var number = document.getElementById("phonenumber").value;
var message = document.getElementById("message").value;

var params = "{'message':'" + message + "', 'number':'" + number + "'}";
$.ajax({
    type: "POST",
    url: "Default.aspx/SendMessage",
    data: params,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        alert("Message sent");
    },
    error: function (msg) {
        alert("Message call failed");
    }
});
}

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

Overriding href attribute with jQuery

I am facing an issue with a div (.questionsList) that contains a link. When I click on the div, an element #slider slides out as desired. However, clicking on the link inside the div causes the slider to slide out instead of following the link's href. ...

Managing multiple dropdown menus in PHP when dealing with Select options

In the given script, I am attempting to manage the selection between a dropdown option and the value of a text field: <script> function check() { var dropdown = document.getElementById("OpType"); var current_value = dropdown.options[dropdown ...

Function "Contains" not Present in Object

Upon executing the code provided below, I encounter the following error message. An issue has arisen: Cannot find function contains in object Is Patient Fasting?/# of Hours->Yes; 12 hours. Here is the snippet of my code: var i = 0; var tempF ...

"Jesting with JavaScript: Thou shall be warned, for undefined does

While running my unit tests with jest, I encountered an error: TypeError: Cannot read properties of undefined (reading 'getVideoTracks') Can anyone provide suggestions on how to properly test the following line using jest? [videoTrack] = (await ...

Sort through a collection of objects depending on various criteria pulled from a separate array of objects

I am working with an array of objects called c, which looks like this: c = [ { name: 'abc', category: 'cat1', profitc: 'profit1', costc: 'cost1' }, { name: 'xyz', catego ...

Tips for transferring JavaScript variables to a database

I am working on a JavaScript application, but I lack experience with JavaScript code. I need to pass variables from JavaScript to a MySQL database. Despite finding some answers and trying to implement them using Ajax and PHP, I am still facing challenges a ...

Encountering an issue with the for loop in React Native when using FlatList

As a beginner in programming, I am eager to dynamically render a list. The Navbar parent component holds the state with different Food Types categories such as Mexican and Chinese, each with its corresponding menu. My goal is to display each Food Type fol ...

Passing arrow functions for input validation rules to the Stancil component in Vue

I am attempting to implement an arrow function as input rules, similar to the setup in Vuetify at https://vuetifyjs.com/en/api/v-input/#rules. My approach involves passing rules within an array using the following code: <body> <div id="ap ...

Instead of using a string in the createTextNode() function, consider utilizing a variable

I am attempting to use JavaScript to add another list item to an unordered list. I want the list item to display dynamic content based on a pre-existing variable. While I can successfully append a list item by using a string, things go awry when I try to i ...

Error: The current component does not have a template or render function specified. Check the <App>

I am a beginner in Vue js and I am facing an issue while running my application. It is showing an empty page with the error message: Component is missing template or render function. at <App>. Additionally, there is also a warning from Vue Router sa ...

Encountering NotFoundHttpException with Jquery Ajax in Laravel 4

Hello everyone! I'm diving into the world of ajax and currently experimenting with sending form input to a controller through a route and then displaying it in a div. Unfortunately, I've hit a roadblock as I keep getting a NotFoundHttpException ...

Changing an image when hovering over text, all without relying on jQuery

For a school project, I am creating a portfolio page that features images with titles underneath. The concept involves hovering over a headline (such as Design Manual, Animation, Storyboard, etc.) to change the image displayed. Clicking on the updated imag ...

What is the best method for transforming a stream into a file with AngularJS?

Currently, I have a server returning a file stream (StreamingOutput). My goal is to convert this file stream into an actual file using AngularJS, javascript, JQuery, or any other relevant libraries. I am looking to display the file in a <div> or ano ...

Performing JSON deserialization in ABAP can be tricky, especially when dealing with JSON field

I received a JSON response as shown below [ { "Status": "00" }, { "Order Due Date": "", "Customer Address": "", "ConsumerId": "", "Amount Paid": "", " ...

Set up OAuth by creating the DefaultConnection database

Within my ASP.NET WebForms 4.5 application, I have implemented a custom membership provider along with a MSSQL database that uses a custom membership scheme. When I create a new user, I simply invoke dc.Users.Add(newUser); within the MembershipUser Crea ...

Display array information within a table using ajax

Currently working with the Zend Framework to develop a website. I have an array called $shadow which contains IDs of individuals. The query for $shadow runs smoothly in the Model and gets called in the Controller without any issues. However, now I need t ...

Tips for utilizing a specific set of row columns when converting to JSON?

My table t has columns a, b, and c. In order to convert rows into a JSON array of objects, I use the following query: SELECT COALESCE(JSON_AGG(t ORDER BY c), '[]'::json) FROM t The result is as expected: [ { "a": ..., "b": ..., ...

A Vue button that toggles between three states depending on the value in an array

In my Vue project, I am working on loading an array when the page loads. I need to check the status of each line item in the array and display a specific button for each status using a 3-way toggle. Although I believe I understand the main concept, I am s ...

What is the best way to enable an image to be moved on top of another image?

Is there a way to allow users to drag around an image that is positioned on top of another image in an HTML file? I want the superimposed image to stay within the boundaries of the underlying image. Any suggestions on how this can be achieved? <html& ...

Storing a Null value in the ASP.NET cache

I came across a question similar to mine here. To prevent unnecessary round trips to the database, I've decided to cache the output. However, ASP.NET seems to struggle with differentiating between a value not being set and an actual NULL value. Is the ...