Pass Multiple Parameters to jQuery ajax call

asp.netJqueryAjax

asp.net Problem Overview


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

asp.net Solutions


Solution 1 - asp.net

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

Solution 2 - asp.net

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

Solution 3 - asp.net

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

Solution 4 - asp.net

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.

Solution 5 - asp.net

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

Solution 6 - asp.net

$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',      
    data: "jewellerId=" + filter+ "&locale=" +  locale,  
    success: AjaxSucceeded,
    error: AjaxFailed
});

Solution 7 - asp.net

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

Solution 8 - asp.net

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 + "'}",

Solution 9 - asp.net

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.

Solution 10 - asp.net

I successfully passed multiple parameters using json

data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value + "'," + "'tempdata':'" +"myvalue" + "'}",

Solution 11 - asp.net

            data: JSON.stringify({ "objectnameOFcontroller": data, "Sel": $(th).val() }),

controller object name

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrisCaView Question on Stackoverflow
Solution 1 - asp.netDarin DimitrovView Answer on Stackoverflow
Solution 2 - asp.netDavid HedlundView Answer on Stackoverflow
Solution 3 - asp.netpixelineView Answer on Stackoverflow
Solution 4 - asp.netSumit JambhaleView Answer on Stackoverflow
Solution 5 - asp.netArielView Answer on Stackoverflow
Solution 6 - asp.netJustinondayView Answer on Stackoverflow
Solution 7 - asp.netJasbir RanaView Answer on Stackoverflow
Solution 8 - asp.netMilind biloniaView Answer on Stackoverflow
Solution 9 - asp.netSubodh PatilView Answer on Stackoverflow
Solution 10 - asp.netuser2739266View Answer on Stackoverflow
Solution 11 - asp.netAmit DigeView Answer on Stackoverflow