Ajax object POST data error

Ajax object POST data error

swamiswami Posts: 4Questions: 2Answers: 0

For EXACTLY the same request done via $.ajax(), I get a successful request (200), but via the datatables ajax object I get 400. Our server is giving the following error:

{"code":99998,"message":"Can not deserialize instance of org.isha.mdm.api.vo.ContactSearchVO out of START_ARRAY token\n at [Source: java.io.ByteArrayInputStream@ed968aa; line: 1, column: 1]"}

Why is there a difference? Is datatables somehow changing the data being passed?

var x = JSON.stringify(
      {"matchValues": {
          "name": "santosh",
          "phone": "",
          "email": "san1@gmail.com",
          "gender":"MALE"
        },
        "start":1,
        "pageSize":10}
    );
    
    $('mytable')
      .dataTable({
        ajax: {
          url: "https://qa-api.isha.in/v1/in/contact/api/contact/search",
          method: "POST",
          contentType: "application/json",
          headers: {
            "X-Application-ID": "2",
            "X-Request-ID": "23455",
            "From": "test2@xyz.com"
          },
          "data": x,
          dataSrc: "result",
          dataType: "json",
          processData: false,
        }

This question has an accepted answers - jump to answer

Answers

  • swamiswami Posts: 4Questions: 2Answers: 0

    I think this is a datatables bug.

    When I use the browser debugger, I can see that the json object is being recognised with reguar $.ajax() call:

    Request payload
    {matchValues: {name: "santosh", email: "san1@gmail.com", gender: "MALE"}, start: 1, pageSize: 10}

    but not when passed as datatables ajax parameter:

    Request Payload
    [object Object]

  • allanallan Posts: 63,813Questions: 1Answers: 10,516 Site admin
    Answer ✓

    You are correct - DataTables currently doesn't accept a string for the ajax option as can be seen in the documentation. Instead, use a function which will extend the object DataTables uses and then stringify that.

        "data": function ( d ) {
          $.extend( d, myJsonObject );
          return JSON.stringify( d );
        }
    

    DataTables can't accept a string here as there are occasions it needs to send data to the server. It could parse a JSON string, but if it isn't JSON in the string, anything it does would probably be wrong.

    Regards,
    Allan

  • swamiswami Posts: 4Questions: 2Answers: 0

    Hi Allan,

    Thanks very much for the quick response. That's helped me a lot! (I think you meant the (ajax.data) option).

    Just a thought... maybe you could allow string to be parsed as JSON if ajax.contantType = "application/json". That might be more intuitive for ppl with the same requirement.

    Kind Regards

    Swami

This discussion has been closed.