-2

My task is to create list items using REST. I used this code

$(document).ready(function () {
createListItemWithDetails('TestList', 'http://sp20139:85', 'TestListRest', function (data) {
    console.log('New task ' + data.d + ' has been created');
}, function (data) {
    console.log(JSON.stringify(data.d));
});
});

function createListItemWithDetails(listName, siteUrl, title, success, failure) {
var itemType = GetItemTypeForListName(listName);
var item = {
    "__metadata": { "type": itemType },
    "Title": title
};
 $.ajax({
    url: siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
    type: "POST",
    contentType: "application/json;odata=verbose",
    data: JSON.stringify(item),
    headers: {
        "Accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: function (data) {    
console.log(data);
        success(data);
    },
    error: function (data) {           
        failure(data);
    }
});
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}

I checked it in the browser console and it runs successfully.

But the problem is that it didn't show any changes in TestList in SP environment.

5
  • Could you check with Fiddler that response from the REST call do you get?
    – ECM4D
    Commented Apr 1, 2015 at 11:12
  • yes i did that but didn't work Commented Apr 1, 2015 at 11:23
  • What does it mean "works successfully"? Does it print the message "'New task ... has been created'" in the console? Commented Apr 1, 2015 at 13:22
  • 1
    How did you run the JavaScript code into Console Application?
    – Hardik
    Commented Apr 2, 2015 at 9:54
  • Hey hardik,i meant console.log in browser window Commented Apr 2, 2015 at 10:29

1 Answer 1

1

Two leads I guess.

First, you may miss authorization Header, but it depends of your list security settings, like for example :

headers: {
        ...
        "Authorization": "Bearer " + UserOrAppToken
        ...
    }

But more likely, I usually also think ContentLength is mandatory :

...
type: "POST",
contentType: "application/json;odata=verbose",
contentLength: XXXX,
data: JSON.stringify(item),
...

Were XXXX is the length of your item variable

var item = {
    "__metadata": { "type": itemType },
    "Title": title
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.