ChasetopherB
ChasetopherB

Reputation: 464

Can't get ajax call with parameters to hit my C# function

Ajax:

var test = "test";

$.ajax(
{
  type: "POST",
  url: "project/function",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  data: { input: test },
  success: function (response) {
    $("#lblMsg").text(response.d);
  },
  failure: function (response) {
    alert(response.d);
  }
});

C# function:

[WebMethod]
public void function(string input)
{
}

The connection is made successfully when I don't include a parameter. I have tried different single and double quote permutations of the 'data' portion of the ajax call, to no avail.

I have also tried setting the dataType to "text" with similar results.

What am I missing?

Upvotes: 0

Views: 1158

Answers (2)

Naveed
Naveed

Reputation: 46

try this one may be resolve your issue

var test = "test";

$(document).ready(function () {
   $.ajax({
          type: "POST",
          url: "project/function",
          contentType: "application/json; charset=utf-8",
          datatype: "json",
          data:JSON.stringify({ 'input': test }),
          success: function (response) {
         $("#lblMsg").text(response.d);
  },
  failure: function (response) {
    alert(response.d);
  }
  });
});

Upvotes: 0

ADyson
ADyson

Reputation: 61973

I would suggest that you shouldn't send your data as JSON. Just remove the

contentType: "application/json; charset=utf-8"

and jQuery will serialise the data into normal url-encoded form data format, which is what the WebMethod is expecting.

Upvotes: 1

Related Questions