Search code examples
jsonsharepoint-2013jquery-ajaxq

Error processing request stream. JSON text specified is not valid


I used this code

function updateListItem(itemId, listName, siteUrl, title, success, failure) {    
var metatdata = "{ '__metadata': { 'type': 'SP.Data.TestListListItem' }, 'Title': "+title+"}"
getListItemWithId(itemId, listName, siteUrl, function (data) {
    $.ajax({
        url: data.__metadata.uri,
        dataType: "json",
        contentType: "application/json;odata=verbose",
        method: "POST",
        body: metatdata,
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "Content-Length":metatdata.length,
            "X-HTTP-Method": "MERGE",
            "If-Match": "*"
        },
        success: function (data) {
            alert("success in ajax");
            console.log("Item in success ajax");
            console.log(data);
            success(data);
        },
        error: function (data) {
            alert("waiting for success in ajax");
            console.log("Item in error ajax");
            console.log(data);
            failure(data);
        }
    });
}, function (data) {
    failure(data);
});

when i checked it using console,it shows "Error processing request stream. JSON text specified is not valid",I think i can't able to read text value from JSON Response and I tried lot.Please help me guys..Thanks in Advance


Solution

  • function updateListItem(itemId, listName, siteUrl, title, success, failure) {
    
    
    getListItemWithId(itemId, listName, siteUrl, function (data) {
        var item = { '__metadata': { 'type': 'Microsoft.SharePoint.DataService.TestListItem' }, 'Title': title };
        $.ajax({
            url: data.__metadata.uri,
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": data.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    }, function(data){
        failure(data);
    });
    }
    function getListItemWithId(itemId, listName, webUrl, success, failure) {
    $.ajax({
        url: webUrl + "/_vti_bin/listdata.svc/" + listName + "(" + itemId + ")",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            success(data.d);
        },
        error: function (data) {
            failure(data.responseJSON.error);           
        }
    });
    }