Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Message: Invalid JSON primitive: ajax jquery method with Webmethod

Tags:

I am using Data value as object literal, instead of concatenating a String as explained in this answer

My code is the following:

$.ajax({    
  url: "../Member/Home.aspx/SaveClient",
  type: "POST",
  async: false,
  dataType: 'json',
  contentType: 'application/json; charset=utf-8',
  data: {
    "projectSoid": ProjectId,
    "startDate": StartDate,
    "endDate": EndDate,
    "clientManager": ClientManager
  },
  success: function(response) {
    if (response.d != "") {

    }
  },
  error: function(response) {
    var r = jQuery.parseJSON(response.responseText);
    alert("Message: " + r.Message);
    alert("StackTrace: " + r.StackTrace);
    alert("ExceptionType: " + r.ExceptionType);
  }
})

and my webmethod is like this :

[WebMethod]
public static string SaveClient(string projectSoid, string startDate, 
     string endDate, string clientManager)
{
    ...
}

But I get the following error:

Message: Invalid JSON primitive: projectSoid

like image 922
Nestor C Avatar asked Mar 08 '13 12:03

Nestor C


1 Answers

With your contentType: 'application/json; charset=utf-8' you are claiming that you will send JSON but currently your data property is not holding JSON.

You need to transform your data to JSON with the JSON.stringify method:

So change your data property to:

data: JSON.stringify({
    "projectSoid": ProjectId,
    "startDate": StartDate,
    "endDate": EndDate,
    "clientManager": ClientManager
}),

You should note that the JSON.stringify method is not natively supported in older browsers so you may need to provide an implementation with using one of the various libraries like:

Douglas Crockford's JSON2 library.

like image 196
nemesv Avatar answered Oct 23 '22 12:10

nemesv