0

i have a doubt in jquery ajax data format. what is the data type of user data when passing from client to server? . if data is passing like data: { // user data} giving 500 error. but if passing like data:'{}' or data:"{}" giving result as success. do i need to enclose the data between '' or "" ?

 $.ajax({
                type: "POST",
                url: "Contact.aspx/add",
                dataType: "json",
                data: '{ "Data": "hii" }',
                contentType: "application/json; charset=utf-8",
                success: function (response) {

                },

                error: function (msg) {
                    alert(msg.status);
                }
            });
       ------c#-------
      [WebMethod]
    public static void add(string Data)
    {
    }
nichu09
  • 882
  • 2
  • 15
  • 44

3 Answers3

0

you need to use JSON.stringify to stringify the obj data.

var jsonData = JSON.stringify({ "Data": "hii" }); 
$.ajax({
                    type: "POST",
                    url: "Contact.aspx/add",
                    dataType: "json",
                    data: jsonData,
                    contentType: "application/json; charset=utf-8",
                    success: function (response) {

                    },

                    error: function (msg) {
                        alert(msg.status);
                    }
                });
           ------c#-------
          [WebMethod]
        public static void add(string Data)
        {
        }
Kishore Sahasranaman
  • 4,013
  • 3
  • 24
  • 50
  • but i can use http post method like below $.post("Contact.aspx/add", { 'Data': '' + JSON.stringify(arr) + '' }, function (result) { }); . here no need any single or double quote. when comparing two post method makes me confuse – nichu09 Oct 19 '15 at 04:32
  • please see the answer http://stackoverflow.com/a/3870116/2074346, you can see the difference. – Kishore Sahasranaman Oct 19 '15 at 04:38
0

It seems like server is expecting a JSON. JSON's are strings with an specific format. in JS you can declare strings with both '' and "". https://en.wikipedia.org/wiki/JSON

Alejandro
  • 1,159
  • 3
  • 16
  • 30
0

you can do it like this:

$.ajax({ type: "POST", url: "Contact.aspx/add", dataType: "json", data:{ Data:"hii", }, success: function (response) { }, });

Hope it helps.