Quantcast
Channel: BizTalkGurus
Viewing all articles
Browse latest Browse all 2977

Blog Post: SP2013: Updating a List using REST in OData format from JavaScript

$
0
0

After wrestling with this tonight for sometime I’ve finally cracked it. SP2013 RTMed and alot of the sample code fails due to the fact that you need to now add ‘..;odata=verbose’ onto pretty much every call to SharePoint.

Basically you get a series of errors such as:

MIMEtypecouldnotbe foundthat matchesthe contenttypeof the response. Noneof the supportedtype(s) 'application/atom+xml;type=entry, application/atom+xml, application/json;odata=verbose

 

Previously alot of the sample code has

$.getJSON(….) as part of the call to the server – as mentioned we now need to add some custom header values of ‘odata=verbose’, so to save you hours of slogging on this, the getJSON call doesn’t allow custom header values. You need to use the $.ajax(…) for these calls.

READING FROM A LIST

function getCustomers() {
 

  // begin work to call across network
  var requestUri = _spPageContextInfo.webAbsoluteUrl +
                "/_api/Web/Lists/getByTitle('CustomersREST')/items/" +
                "?$select=Id,FirstName,Title,WorkPhone" +
                "&$orderby=Title,FirstName";
   
  var requestHeaders = {
      "accept": "application/json;odata=verbose"
  }
    // execute AJAX request
  $.ajax({
      url: requestUri,
      type: 'GET',
      dataType: 'json',
      headers: requestHeaders,
      success: onDataReturned,
      error: onError
  });
}

 

UPDATING A LIST ITEM

//Sample code to update a Customer List Item in a Customer List called ‘CustomersREST’

function updateCustomer(dialogResult, returnValue) {

  if (dialogResult == SP.UI.DialogResult.OK) {
    var Id = returnValue.Id;
    var FirstName = returnValue.FirstName;
    var LastName = returnValue.LastName;
    var WorkPhone = returnValue.WorkPhone;
    var etag = returnValue.etag;

    var requestUri = _spPageContextInfo.webAbsoluteUrl +
              "/_api/Web/Lists/getByTitle('CustomersREST')/items(" + Id + ")";

    var customerData = {
      __metadata: { "type": "SP.Data.CustomersRESTListItem" },
      Title: LastName,
      FirstName: FirstName,
      WorkPhone: WorkPhone
    };

    requestBody = JSON.stringify(customerData);

    var requestHeaders = {
        "accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
        "X-HTTP-Method": "MERGE",
        "content-length": requestBody.length,
        "content-type" : "application/json;odata=verbose",
        "If-Match": etag
    }

    $.ajax({
      url: requestUri,
      type: "POST",
      contentType: "application/json;odata=verbose",
      headers: requestHeaders,
      data: requestBody,
      success: onSuccess,
      error: onError
    });

  }

}


Blog Post by: Mick Badran

Viewing all articles
Browse latest Browse all 2977

Trending Articles