13

I am trying to send json data from the client to my server using this:

$.ajax({
    url : 'http://127.0.0.1:8001/api/v1/pulse/7/',
    data : data,
    type : 'PATCH',
    contentType : 'application/json'
)};

I get a No JSON object could be decoded. However when i use PUT the json object gets sent.

It only doesnt work for PATCH

The backend is Django and the app im using is tastypie

David G
  • 94,763
  • 41
  • 167
  • 253
nknj
  • 2,436
  • 5
  • 31
  • 45

3 Answers3

17

First, check that you use latest version of jQuery library:

  • Older versions directly restrict unknown methods (PATCH is new one).
  • I've tested on jQuery 1.7 - PATCH method working without problems.

Second, not all browsers supports PATCH method using XMLHttpRequest:

  • Like, IE 7,8 (9+ works okay) have XMLHttpRequest, but it throws an error on PATCH:

    new XMLHttpRequest().open('PATCH', '/'); //Illegal argument
    
  • To fix this, you may force jQuery to use the old proprietary ActiveXObject xhr, like so:

    $.ajax({
        url : 'http://127.0.0.1:8001/api/v1/pulse/7/',
        data : data,
        type : 'PATCH',
        contentType : 'application/json',
        xhr: function() {
            return window.XMLHttpRequest == null || new window.XMLHttpRequest().addEventListener == null 
                ? new window.ActiveXObject("Microsoft.XMLHTTP")
                : $.ajaxSettings.xhr();
        }
    });          
    
Eric Brandel
  • 860
  • 7
  • 9
vitrilo
  • 1,437
  • 16
  • 20
16

A bit late, but this worked for me when I got this error:

$.ajax({
  url : 'http://127.0.0.1:8001/api/v1/pulse/7/',
  data : JSON.stringify(data),
  type : 'PATCH',
  contentType : 'application/json',
  processData: false,
  dataType: 'json'
});

Serializing the object yourself instead of letting jQuery do it seems to help. This works for me on the latest version of Chrome, but still doesn't fix the ie problems mentioned in other responses.

Amit Tomar
  • 4,800
  • 6
  • 50
  • 83
turtlemonvh
  • 9,149
  • 6
  • 47
  • 53
3
var request = new XMLHttpRequest();
request.open('PATCH', 'http://127.0.0.1:8001/api/v1/pulse/6/', false);
request.setRequestHeader("Content-type","application/json");
request.send('{"isActive": 1}');

Using a an XMLHttpRequest solves it!

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
nknj
  • 2,436
  • 5
  • 31
  • 45