Search code examples
sharepointspservices

How to update a page's content using SPServices?


I am trying to update a Page's content using SPServices.

When I run my code, it does update the correct page, but instead of updating the content, it just removes the content.

var newContent = "<p>This is a test</p>";

$().SPServices({
   operation: "UpdateListItems",
   listName: "Pages",
   ID: itemID,
   async: false,
   valuepairs: [["PublishingPageContent", newContent]]
})

Solution

  • It occurs since UpdateListItems operation expects HTML escaped string as a a parameter.

    The following function could be used for encoding HTML string:

    function htmlEncode(value){
      //create a in-memory div, set it's inner text(which jQuery automatically encodes)
      //then grab the encoded contents back out.  The div never exists on the page.
      return $('<div/>').text(value).html();
    }
    

    Source

    Fixed example

    var itemID = <Your item id goes here>;
    var newContent = "<p>Some content goes here</p>";
    $().SPServices({
       operation: "UpdateListItems",
       listName: "Pages",
       ID: itemID,
       async: false,
       valuepairs: [["PublishingPageContent", htmlEncode(newContent)]],
       completefunc: function(xData, Status)
       {
             console.log('Page has been updated');      
       }
    });