Pass Multiple Parameters to jQuery ajax call

ChrisCa picture ChrisCa · Dec 16, 2009 · Viewed 324.5k times · Source

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

Answer

Darin Dimitrov picture Darin Dimitrov · Dec 16, 2009

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