Calling .Net webservice with Jquery is causing woe when trying to post data Calling .Net webservice with Jquery is causing woe when trying to post data ajax ajax

Calling .Net webservice with Jquery is causing woe when trying to post data


I think the webservice expects the parameter json to be set. Try this AJAX call :

var data = {'name':'niall'};$.ajax({    type: "POST",    url: "/WebServices/BasketServices.asmx/AddItemToBasket",    data: "json=" + JSON.stringify(data),    contentType: "application/json; charset=utf-8",    dataType: "json",    success: OnItemAddedSuccess});

where JSON.stringify() is a method like the one found in the "official" implementation : http://json.org/js.html


The solution above did not work for me. So instead i did the following.1.) make sure the the javascript object-properties (here ID and Quantity) do have the same name and the same type (in this case number == int) as the parameter of your webservice2.) do not wrap the object into a Data Transfer Object (DTO), but instead just stringify themThanks goes to Yasin Tarim which gave the hints i needed to get it working

// javascript objectvar cartItem = {"ID": 123, "Quantity": 2}$.ajax({    type: "POST",    url: "/WebServices/BasketServices.asmx/AddItemToBasket",    data: JSON.stringify(cartItem),    contentType: "application/json; charset=utf-8",    dataType: "json",    success: function (data) { OnSuccess(cartItem, data); },});
    // ASMX Server Side Code    [WebMethod(Description = "Add item to ShoppingCart")]    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]            public string AddItemToBasket(int ID, int Quantity)     {                    CartItem cI = new CartItem();        cI.iD = ID;        cI.qty = Quantity;        CartItem.SaveToDatabase(ci);        return "foo from Webservice - it worked";    }


This should work. You should pass json as a string, with a parameter name 'json' (which is the same as parameter name in your web method.

data: "{json: '{\'name\':\'niall\'}'}",