[asp.net] Pass Multiple Parameters to jQuery ajax call

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

This question is related to asp.net jquery ajax

The answer is


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.


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

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

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

controller object name


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.


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

I successfully passed multiple parameters using json

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

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


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

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

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios