views:

55

answers:

2

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.

+1  A: 

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).

Pointy
This is correct, strings need to be quoted in JSON.
Daniel Coffman
@Daniel - Safer to pass it as a variable like I have...otherwise a string containing a `'` means trouble. With the pair syntax jQuery will take care of this.
Nick Craver
Noted, thank you.
Daniel Coffman
@Nick this way of doing it is working, but yours isn't. Any ideas?
iboeno
@iboeno - Depends on the server in that case, try `{'id':elementValue}`
Nick Craver
@Nick hmm...no luck
iboeno
+2  A: 

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
        }
});
Nick Craver