Inserting/Updating SharePoint List via JQuery

MLEONKC 1 Reputation point
2022-03-16T10:30:05.707+00:00

I used to have the code to do this but cannot find it anymore. How can I update or add a list item via JQuery?

The code was something like:

var batch....

var soapEnv....

$.ajax....

function processResult....

Microsoft 365 and Office SharePoint Server Development
Developer technologies ASP.NET Other
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Rob Windsor 2,001 Reputation points
    2022-03-16T12:37:45.757+00:00

    If you are targeting an on-premises version of SharePoint, you can use a Script Editor or Content Editor web part and code similar to that shown in this blog post: Update ListItem in SharePoint using REST API

    function UpdateListItemUsingItemId(Id) {  
           $.ajax   
            ({  
                  // _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.  
            // You can replace this with other site URL where you want to apply the function  
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('list name')/items(" + Id +")",  
            type: "POST",          
            headers:   
            {   
                // Accept header: Specifies the format for response data from the server.  
                "Accept": "application/json;odata=verbose",  
                //Content-Type header: Specifies the format of the data that the client is sending to the server  
                "Content-Type": "application/json;odata=verbose",  
                // IF-MATCH header: Provides a way to verify that the object being changed has not been changed since it was last retrieved.  
                // "IF-MATCH":"*", will overwrite any modification in the object, since it was last retrieved.  
                 "IF-MATCH": "*",  
                //X-HTTP-Method:  The MERGE method updates only the properties of the entity , while the PUT method replaces the existing entity with a new one that you supply in the body of the POST  
                "X-HTTP-Method": "MERGE",  
                // X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header  
                "X-RequestDigest": $("#__REQUESTDIGEST").val()  
            },  
             data: JSON.stringify({  
             __metadata:  
                {  
                  // Format of the "type" is: SP.Data.<<ListName>>ListItem. First character of the <<ListName>> should be in Capital  
                  type: "SP.Data.List_x0020_NameListItem"  
                },  
                description: "Updated Description"  
            }),  
            success: function(data, status, xhr)   
            {   
                console.log("Success");       
            },   
            error: function(xhr, status, error)   
            {   
                console.log("Failed");  
            }   
        });  
    }  
    

    If you are targeting SharePoint Online, then you will want to use the SharePoint Framework an code similar to that shown in this Microsoft Learn module: Work with SharePoint Content using the SharePoint Framework

    private _updateListItem(): Promise<SPHttpClientResponse> {  
      // get the first item  
      return this.context.spHttpClient.get(  
          this.context.pageContext.web.absoluteUrl + `/_api/web/lists/getbytitle('Countries')/items?$select=Id,Title&$filter=Title eq 'United States'`,  
          SPHttpClient.configurations.v1)  
        .then(response => {  
          return response.json();  
        })  
        .then(jsonResponse => {  
          return jsonResponse.value[0];  
        })  
        .then((listItem: ICountryListItem) => {  
          // update item  
          listItem.Title = 'USA';  
          // save it  
          const request: any = {};  
          request.headers = {  
            'X-HTTP-Method': 'MERGE',  
            'IF-MATCH': (listItem as any)['@odata.etag']  
          };  
          request.body = JSON.stringify(listItem);  
      
          return this.context.spHttpClient.post(  
            this.context.pageContext.web.absoluteUrl + `/_api/web/lists/getbytitle('Countries')/items(${listItem.Id})`,  
            SPHttpClient.configurations.v1,  
            request);  
        });  
    }  
    

    Both of these examples are using the SharePoint REST API to perform the update. For more information on working with lists and list items with the SharePoint REST API, see Working with lists and list items with REST

    0 comments No comments

  2. Tong Zhang_MSFT 9,251 Reputation points
    2022-03-17T02:34:29.937+00:00

    Hi @MLEONKC :
    Based on my testing and research, you can refer to the following code to create and update lists:

    function CreateList() {  
        $.ajax  
            ({  
                // _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.  
                // You can replace this with other site URL where you want to apply the function  
       
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/",  
                type: "POST",  
                data: JSON.stringify  
            ({  
                __metadata:  
                {  
                    type: "SP.List"  
                },  
                Title: "List Name",  
                Description: "New List Description",  
                BaseTemplate: 100  
            }),  
                headers:  
            {  
                "Accept": "application/json;odata=verbose",  
                "Content-Type": "application/json;odata=verbose",  
                "X-RequestDigest": $("#__REQUESTDIGEST").val()  
            },  
                success: function (data, status, xhr) {  
                    console.log("success");  
                },  
                error: function (xhr, status, error) {  
                    console.log("Failed");  
                }  
            });  
    }  
    
    function SetListTitle() {  
        $.ajax  
            ({  
                // _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.  
                // You can replace this with other site URL where you want to apply the function  
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Documents')",  
                // The HTTP request method: GET for read operations and POST for write operations.  
                // POST requests can perform update or delete operations by specifying a DELETE, MERGE, or PUT verb in the X-HTTP-Method header.  
                type: "POST",  
                headers:  
            {  
                // Accept header: Specifies the format for response data from the server.  
                "Accept": "application/json;odata=verbose",  
                //Content-Type header: Specifies the format of the data that the client is sending to the server  
                "Content-Type": "application/json;odata=verbose",  
                // IF-MATCH header: Provides a way to verify that the object being changed has not been changed since it was last retrieved.  
                // "IF-MATCH":"*", will overwrite any modification in the object, since it was last retrieved.  
                "IF-MATCH": "*",  
                //X-HTTP-Method:  The MERGE method updates only the properties of the entity , while the PUT method replaces the existing entity with a new one that you supply in the body of the POST  
                "X-HTTP-Method": "MERGE",  
                // X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header  
                "X-RequestDigest": $("#__REQUESTDIGEST").val()  
            },  
                data: JSON.stringify  
            ({  
                __metadata:  
                {  
                    type: "SP.List"  
                },  
                Title: "New Title"  
            }),  
                success: function (data, status, xhr) {  
                    console.log("success");  
                },  
                error: function (xhr, status, error) {  
                    console.log("Failed");  
                }  
            });  
    }  
    

    Reference:
    working-with-lists-and-list-items-with-rest


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.



  3. sadomovalex 3,636 Reputation points
    2022-03-22T15:17:07.853+00:00

    with Sharepoint Online it is also possible to use pnp js. Code is very simple in this case:

    import { spfi, SPFx } from "@pnp/sp";
    import "@pnp/sp/webs";
    import "@pnp/sp/lists";
    import "@pnp/sp/items";
    import { IItemAddResult } from "@pnp/sp/items";
    
    const sp = spfi("{tenant url}").using(SPFx(this.context));
    
    // add an item to the list
    const iar: IItemAddResult = await sp.web.lists.getByTitle("My List").items.add({
      Title: "Title",
      Description: "Description"
    });
    

    Here you may find more examples: https://pnp.github.io/pnpjs/sp/items/#add-items.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.