114

I have the following jquery code to call a webmethod in an aspx page

$.ajax({
    type: "POST",
    url: "popup.aspx/GetJewellerAssets",
    contentType: "application/json; charset=utf-8",
    data: '{"jewellerId":' + filter + '}',
    dataType: "json",
    success: AjaxSucceeded,
    error: AjaxFailed
});

and here is the web method signature

[WebMethod]
public static string GetJewellerAssets(int jewellerId)
{

This works fine.

But now I need to get two parameters passed to the web method

the new web method looks like this

[WebMethod]
public static string GetJewellerAssets(int jewellerId, string locale)
{
}

How do I change the client code to successfully call this new method signature ?

EDIT:

The following 2 syntaxes worked

data: '{ "jewellerId":' + filter + ', "locale":"en" }',

and

data: JSON.stringify({ jewellerId: filter, locale: locale }),

where filter and locale are local variables

Mikhail
  • 9,186
  • 4
  • 33
  • 49
ChrisCa
  • 10,876
  • 22
  • 81
  • 118
  • 9
    `data: JSON.stringify({ jewellerId: filter, locale: locale })` is the best way which I every found, Thank @ChrisCa – Frank Myat Thu Mar 14 '12 at 07:37
  • If you're a sad soul like me, you might have gotten stuck on this for hours. When using `JSON.stringify` with an object literal, you MUST include the parameter name with a colon, all wrapped inside `{}` braces. Using `JSON.stringify(objectLiteral)` doesn't work. – Kaleb Anderson Nov 12 '15 at 22:14
  • Method signature like `[WebMethod] [ScriptMethod(UseHttpGet = true)] public static string TestIBAN(string ccc)` ? – Kiquenet Mar 04 '16 at 08:45

11 Answers11

159

Don't use string concatenation to pass parameters, just use a data hash:

$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',
    contentType: 'application/json; charset=utf-8',
    data: { jewellerId: filter, locale: 'en-US' },
    dataType: 'json',
    success: AjaxSucceeded,
    error: AjaxFailed
});

UPDATE:

As suggested by @Alex in the comments section, an ASP.NET PageMethod expects parameters to be JSON encoded in the request, so JSON.stringify should be applied on the data hash:

$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ jewellerId: filter, locale: 'en-US' }),
    dataType: 'json',
    success: AjaxSucceeded,
    error: AjaxFailed
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 12
    Consider also using `JSON.stringify( myObject )` to create a JSON string from a javascript object, in case you want to group your parameters to a class later on. – Alex Bagnolini Dec 16 '09 at 17:40
  • 1
    thanks for the replies - however, I get a http status 500 when I try it like that. Any ideas? or even how to debug it? Breakpoint in the web method never gets hit – ChrisCa Dec 16 '09 at 17:55
  • 1
    new code as follows $.ajax({ type: 'POST', url: 'popup.aspx/GetJewellerAssets', contentType: 'application/json; charset=utf-8', data: {jewellerId:filter,locale:'en-US'}, dataType: "json", success: AjaxSucceeded, error: AjaxFailed }); – ChrisCa Dec 16 '09 at 17:56
  • 1
    To debug, first look at FireBug what's the exact response of the server, then put a break point in the web service method and see if it is reached. – Darin Dimitrov Dec 16 '09 at 18:08
  • 1
    Breakpoint in the web method never gets hit Firebug shows: "Message":"Invalid JSON primitive: jewellerId.","StackTrace":" at System.Web.Script.Serialization So I guess the syntax of the json is incorrect – ChrisCa Dec 16 '09 at 18:12
  • 1
    As @Alex suggested you need to use `JSON.stringify` like this: `data: JSON.stringify({ jewellerId: 1, locale: 'en-US' })` – Darin Dimitrov Dec 16 '09 at 18:19
18
data: '{"jewellerId":"' + filter + '","locale":"' + locale + '"}',
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • 1
    this worked: '{ "jewellerId":' + filter + ', "locale":"en" }', (obviously I won't be hardcoding the locale to en, but this is the syntax that worked. – ChrisCa Dec 17 '09 at 09:29
  • This worked for me with MVC 3. I couldn't get Darin's way to work - maybe its an MVC 3 thing. – fiat May 30 '12 at 01:06
8

simply add as many properties as you need to the data object.

 $.ajax({
                    type: "POST",
                    url: "popup.aspx/GetJewellerAssets",
                    contentType: "application/json; charset=utf-8",
                    data: {jewellerId: filter , foo: "bar", other: "otherValue"},
                    dataType: "json",
                    success: AjaxSucceeded,
                    error: AjaxFailed
                });
pixeline
  • 17,669
  • 12
  • 84
  • 109
  • 2
    What would the webmethod signature look like in this case to read out the properties in `data` on the server side? – Adam Aug 18 '17 at 02:13
7

DO not use the below method to send the data using ajax call

data: '{"jewellerId":"' + filter + '","locale":"' + locale + '"}'

If by mistake user enter special character like single quote or double quote the ajax call fails due to wrong string.

Use below method to call the Web service without any issue

var parameter = {
       jewellerId: filter,
       locale : locale 
};


data: JSON.stringify(parameter)

In above parameter is the name of javascript object and stringify it when passing it to the data attribute of the ajax call.

Sumit Jambhale
  • 565
  • 8
  • 13
4
$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',      
    data: "jewellerId=" + filter+ "&locale=" +  locale,  
    success: AjaxSucceeded,
    error: AjaxFailed
});
ebram khalil
  • 8,252
  • 7
  • 42
  • 60
Justinonday
  • 137
  • 3
  • 15
3

Has anyone else noticed that the json string/object is invalid in all answers except for David Hedlund's? :)

JSON objects must be formatted in the following manner: {"key": ("value" | 0 | false)}. Also, writing it out as a string requires much less than stringifying the object...

Ariel
  • 4,502
  • 2
  • 21
  • 23
2
    var valueOfTextBox=$("#result").val();
    var valueOfSelectedCheckbox=$("#radio:checked").val();

    $.ajax({
    url: 'result.php',
    type: 'POST',
    data: { forValue: valueOfTextBox, check : valueOfSelectedCheckbox } ,
    beforeSend: function() {

          $("#loader").show();
       },
    success: function (response) {
       $("#loader").hide();
       $("#answer").text(response);
    },
    error: function () {
        //$("#loader").show();
        alert("error occured");
    }
    }); 
Jasbir Rana
  • 259
  • 3
  • 13
1

Just to add on [This line perfectly work in Asp.net& find web-control Fields in jason Eg:<%Fieldname%>]

 data: "{LocationName:'" + document.getElementById('<%=txtLocationName.ClientID%>').value + "',AreaID:'" + document.getElementById('<%=DropDownArea.ClientID%>').value + "'}",
0

Its all about data which you pass; has to properly formatted string. If you are passing empty data then data: {} will work. However with multiple parameters it has to be properly formatted e.g.

var dataParam = '{' + '"data1Variable": "' + data1Value+ '", "data2Variable": "' + data2Value+ '"' +  '}';

....

data : dataParam

...

Best way to understand is have error handler with proper message parameter, so as to know the detailed errors.

Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
Subodh Patil
  • 82
  • 1
  • 9
0

I successfully passed multiple parameters using json

data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value + "'," + "'tempdata':'" +"myvalue" + "'}",
Matt
  • 74,352
  • 26
  • 153
  • 180
-1
            data: JSON.stringify({ "objectnameOFcontroller": data, "Sel": $(th).val() }),

controller object name