Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send JSON to webmethod?

How can i send a JSON object to a webmethod using jQuery?

like image 340
Hannoun Yassir Avatar asked Oct 06 '09 19:10

Hannoun Yassir


2 Answers

Please refer to this article by Dave Ward. It is a complete tutorial on doing this stuff. Also you will find there other great jquery/ASP.net stuff.

EDIT:- Dave is calling method without any arguments, you can replace empty data property with actual data you want to send:

$.ajax({
  type: "POST",
  url: "Default.aspx/GetDate",
  data: "{'name':'tiger1','hobbies':['reading','music']}",//PUT DATA HERE
  contentType: "application/json; charset=utf-8",
  dataType: "json",
like image 187
TheVillageIdiot Avatar answered Oct 07 '22 16:10

TheVillageIdiot


WebMethods expect a string containing JSON that will be parsed on the server-side, I use the JSON.stringify function to convert a parameters object to string, and send the data, I have a function like this:

jQuery.executePageMethod = function(location, methodName, methodArguments,
                                    onSuccess, onFail) {
    this.ajax({
        type: "POST",
        url: location + "/" + methodName,
        data: JSON.stringify(methodArguments), // convert the arguments to string
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data, status) {
            var jsonData = JSON.parse(data.d);
            onSuccess(jsonData, status);
        },
        fail: onFail
    });
};

I recommend you to include the json2.js parser in your pages, to have the JSON.stringify function cross-browser available.

like image 43
Christian C. Salvadó Avatar answered Oct 07 '22 17:10

Christian C. Salvadó