+1  A: 

Request and response headers are different storys. Thus, it's not necessary to send a specific datatype in order to receive it.

In the case of jQuery, just use the underlaying .ajax() function with dataType set to 'json'. The rest depends on your calling script/service.

Kind Regards

--Andy

jAndy
Hi jAndy,Thanks for the reply. My problem is that if I omit the contentType but set the dataType, the contentType defaults to urlencoded, which is correct but the data returned from the webservice is encoded as xml not json as I would like. It seems like the dataType is ignored unless the contentType is also set to json.
Click Ahead
+1  A: 

You should also set the contentType in the JSON request as well. This will ensure you don't have application/x-www-form-urlencoded in the request. Instead, it will give you want you want: application/json; charset=utf-8.

$.ajax({
    url: '/your/site',
    contentType: 'application/json',
    dataType: 'json',
    data: jsonString,
    type: 'post',
    success: function (data) {
        /* do stuff */
    }
});
Taylor Leese
Hi Talor L,My problem with this is that I don't want to post the data as json, I want to post it as urlencoded. I do however want to return json from my webservice but if I don't set the contentType to json I get back xml (even if the dataType is set to json).
Click Ahead
Sounds like this is an issue with your web service. Here's a related question: http://stackoverflow.com/questions/288850/how-to-return-json-from-a-2-0-asmx-web-service
Taylor Leese
A: 

Hi!

If you will use WFC RESTfull Service instead of .asmx webservice you can implement all your requirements from your question. But usage of .asmx webservice with JSON as output required that you use at least contentType: 'application/json'. In different places you can find as a reason - security reason (see JSON Hijacking).

Probably 'x-www-form-urlencoded' is not your real problem. If you use dataType: "json" the parameters will be also send in the form "test1=value1&test2=value2"!!! The only difference, that all values should be JSON encoded. And jQuery don't makes JSON encoding of the data. (You can look in the code of jQuery.) The main difference is only that "Accept: application/json" will be explicitly set in the request header.

Look at http://stackoverflow.com/questions/2651091/jquery-ajax-call-to-httpget-webmethod-c-not-working/2656543#2656543 which I wrote recently. In this post was asked example of GET request. But it is almost the same. The only difference is, that data after encoding will be appended to the URL (for GET request). For POST request the data will be send in body. By the way if one set "processData: false" (see http://api.jquery.com/jQuery.ajax/) the GET data will be also send inside of body. So read my code example from http://stackoverflow.com/questions/2651091/. I hope you receive ideas how you can implement what you will.

I think you had problems with encoding complex data for your .asmx webservice call. Here is example with "complex" data:

[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public OutputData AjaxGetMore (InputData input) {
    return new OutputData () {
        id = input.id,
        message = new List { "it's work!", "OK!" },
        myInt = new int[] { input.myInt[0] + 1, input.myInt[1] + 1, 20, 75 },
        myComplexData = new InternalData () { blaBla = "haha", iii = new int[] { 1, 2, 3, 4, 5 } }
    };
}

where

public class InternalData {
    public string blaBla { get; set; }
    public int[] iii { get; set; }
}
public class OutputData {
    public string id { get; set; }
    public List message { get; set; }
    public int[] myInt { get; set; }
    public InternalData myComplexData { get; set; }
}
public class InputData {
    public string id { get; set; }
    public int[] myInt { get; set; }
    public InternalData data { get; set; }
}

and on the client side

var myData = { id: "li1234", myInt: [100, 200], data : {blaBla: "Hahhh!", iii: [10,20,30]}}
var myDataForjQuery = {input:$.toJSON(myData)};
$.ajax({
    type: "GET",
    url: "/Service1.asmx/AjaxGetMore", // + idAsJson,
    data: myDataForjQuery, // idAsJson, //myData,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(msg) {
        // var msg = {__type: "Testportal.outputData", id: "li1234", message: "it's work!", myInt:101}
        alert("message=" + msg.d.message + ", id=" + msg.d.id + ", myInt=" + msg.d.myInt); 
    },
    error: function(res, status) {
        if (status ==="error") {
            // errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
            var errorMessage = $.parseJSON(res.responseText);
            alert(errorMessage.Message);
        }
    }
});

($.toJSON come from the JSON plugin ) You can modify this example to HTTP POST, if you want.

One more small advice. If you use jQuery 1.4.x you can try use 'none' as dataType. See documentation: "If none is specified, jQuery will intelligently try to get the results, based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string)"

Best regards

Oleg
Hi Oleg,Thanks for the long response !! After much trying I concluded that the only way to return json data from my webservice was to set the contentType to 'application/json' as stated. I decided against this approach because I didn't want to go down the path of serializing a simple form as json just for the sake of posting it especially since any functionality to do this is not supported by default in all browsers. In the end I decided that the best approach is to use ASP.NET MVC, which provides 'out of the box' json support via the JSONResult in the Controller. Thanks for the help :)
Click Ahead
You welcome. I like and use ASP.NET MVC also. I decide to place all business logic inside of WFC as a data provide. It was pure architecture decision. But for you project ASP.NET MVC could be the best one. ASP.NET MVC is the most flexible from the 3 ways: WFC, MVC and .asmx webservice. Goog luck and much pleasure in software development!
Oleg