Thursday, February 2, 2017

Create List Items using rest Api in SharePoint

You can create lists records using the powerful rest API that SharePoint provide.

Here is an example how you can do it



<script src="https://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
function AddListItem() {
         var category = $("select[id$='ddlcategory'] option:selected").text();
        var feedback = $("[id$='txtfeedback']").val();
        $.ajax
            ({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('Feedback')/Items",
                type: "POST",
                data: JSON.stringify
                ({
                    __metadata:
                    {
                        type: "SP.Data.FeedbackListItem"
                    },
                    Title: category,
                    Feedback: feedback
                   
                }),
                headers:
                {
                    "Accept": "application/json;odata=verbose",
                    "Content-Type": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "X-HTTP-Method": "POST"
                },
                success: function (data, status, xhr) {

                },
                error: function (xhr, status, error) {

                }
            });
    
    }
</script>
I created this function to create list records in my Feedback list.
I am getting a string value from a text box and from one select box and passing these value to list fields and called this function on button click.

You have to take care of the below code

  data: JSON.stringify
                ({
                    __metadata:
                    {
                        type: "SP.Data.FeedbackListItem"    // This is the list title and the syntax to create item
                    },
                    Title: category,  //These are internal names of fields to which you will be passing values
                    Feedback: feedback
                   
                }),

Happy Coding !!!

No comments:

Post a Comment