yoyo
yoyo

Reputation: 79

Jquery Ajax POST Request sending data issue

I have searched a lot and not been able to find a working solution to why my post request is not sending it's data to the server. I can send the request without data and I get my results from the server, but I just cannot send my data to the server. I have narrowed it down to the "data" attribute and assume I am just doing something wrong. Thank you.

Client

var scriptURL = "default/scripts/serverside/Scripts.aspx";
$.ajax({
    type: "POST",
    url: baseURL + scriptURL + "/SaveItem",
    data: "{}",                                           //works (to return a result)
    //data: "{sendData: '" + dataPackage + "'}",            //does not work
    //data: dataPackage,                                    //does not work
    //data: { sendData: dataPackage },                      //does not work
    //data: { "sendData": dataPackage },                    //does not work
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        de("server result:" +result);
    }
});

Server

[WebMethod]
public static string SaveItem(string sendData)
{
    string result = "received: " + sendData;
    return result;
}

Please help, I just cant seem to get it working and know it has got to be a syntax issue...

Similar problems I have found (but no working answers):

Upvotes: 0

Views: 5761

Answers (2)

margabit
margabit

Reputation: 2954

Try this one:

$.ajax({
   type: "POST",
   url: baseURL + scriptURL + "/SaveItem",
   data: $.toJSON({ sendData: dataPackage }),                      
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: function (result) {
       de("server result:" +result);
   }
});

The toJSON will convert your JS object into a proper JSON string. You could also use JSON.stringify

Upvotes: 1

SR5
SR5

Reputation: 95

Try this:

var scriptURL = "default/scripts/serverside/Scripts.aspx";
$.ajax({
    type: "POST",
    url: baseURL + scriptURL + "/SaveItem",
    data: {sendData: "string to send" }
    dataType: "json",
    success: function (result) {
        de("server result:" +result);
    }
});

Upvotes: 0

Related Questions