Reputation: 3879
I'm using ASP.NET and attempting to call a method with a signature of
[WebMethod]
public static string GetInfo(string id){...}
using the following javascript:
var elementValue = $("#element").attr('id');
var d = "{id : " + elementValue + "}";
$.ajax({
type: "POST",
url: "../WebPage.aspx/GetInfo",
data: d,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//do this
}
});
And this is not working. If instead I set elementValue = 2;
it works fine. If I try to hardcode in a string value for testing purposes e.g. elementValue = "nameToLookUp";
It fails. Why is this happening, and how do I resolve it?
On a side not, why is type:
required to be POST
instead of a GET
? In the end I just want to pass a string value I want to look up in a DB and retrieving some json data.
Upvotes: 0
Views: 968
Reputation: 630389
You should quote the parameters or change your syntax around like this:
var elementValue = $("#element").attr('id');
$.ajax({
type: "POST",
url: "../WebPage.aspx/GetInfo",
data: {'id':elementValue},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//do this
}
});
Upvotes: 2
Reputation: 413709
To encode a string, it needs to be quoted (inside your string of JSON)
var d "{id: '" + elementValue + "'}";
The "type" is not required to be "POST" by jQuery; what makes you feel that it is? Now, your server code might require it, but that's something I can't help with (in this specific case).
Upvotes: 1