Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQuery PATCH to make partial update

Alright, my URL(example.com/api/content/12) returns JSON data in the following format:

{
    "title" : "My blog post",
    "body" : "Body",
    "data" : "old"
}

I want to simply make a change to the data field only. Currently, I am using PUT and basically just replacing the whole thing, which I realize is ineffecient. Something like this:

var data = {
    "title" : "My blog post",
    "body" : "Body",
    "data" : "New data"
}

$.ajax({
   url: 'http://example.com/api/content/12',
   data: data,
   error: function() {
      console.log('Error');
   },
   dataType: 'json',
   success: function(data) {
      console.log('success');
   },
   type: 'PUT'
});

How do I do this with PATCH? I dont really need to send the title and body fields as they do not change. I just want to update the data field.

like image 780
darkhorse Avatar asked Aug 14 '16 19:08

darkhorse


1 Answers

For the specified use case the simplest approach is to use JSON Merge Patch like so:

var patch = {
    "data" : "New data"
}

$.ajax({
   type: 'PATCH',
   url: 'http://example.com/api/content/12',
   data: JSON.stringify(patch),
   processData: false,
   contentType: 'application/merge-patch+json',

   /* success and error handling omitted for brevity */
});

processData: false and data: JSON.stringify(patch) overrides jQuery's default serialization for PATCH (which isn't JSON) and forces JSON serialization.

Note that JSON Merge Patch has inherent limitations (e.g. you cannot update only some elements in an array, there is no way to set keys to null etc.), so for more complex implementations I would encourage the OP to consider JSON Patch:

var patch = [
    { "op": "replace", "path": "/data", "value": "New data" },
]

$.ajax({
   type: 'PATCH',
   url: 'http://example.com/api/content/12',
   data: JSON.stringify(patch),
   processData: false,
   contentType: 'application/json-patch+json',

   /* success and error handling omitted for brevity */
});
like image 79
chopper Avatar answered Oct 17 '22 15:10

chopper