Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Create a sharepoint list item using javascript. using lists.asmx webservice

3.00/5 (3 votes)
19 Nov 2009CPOL 33.1K  
You can call the CreateListItem function (below) in your webpart code to create a sharepoint list item. CreateListItem function further calls CreateSoap function to create a list item.In ws.open use your server name (see the url below). If you are using the below code in a subsite then use the u

You can call the CreateListItem function (below) in your webpart code to create a sharepoint list item. CreateListItem function further calls CreateSoap function to create a list item.

In ws.open use your server name (see the url below). If you are using the below code in a subsite then use the url of subsite in ws.open to open up the lists.asmx

eg, use http://servername/subsite1/subsite2/_vti_bin/lists.asmx when you are using code in subsite2.

function CreateListItem(Title)
 {  
                           
    var soap1 = createEnvelope(Title);
                
    var ws = new ActiveXObject("Microsoft.XMLHTTP");    
      if(ws == null) 
       return null;
            
    ws.open("POST", 
         "http://servername/_vti_bin/lists.asmx",
         false);
    ws.setRequestHeader("Content-Type", "text/xml; charset=utf-8");            
    ws.setRequestHeader("SOAPAction", 
        "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems">
        http://schemas.microsoft.com/sharepoint/soap/UpdateListItemsquot;);
    ws.send(soap1);  
    //   alert(soap1);
           
}     
  function createEnvelope(Title)
{               
         
    var soap = '<?xml version=\"1.0\" encoding=\"utf-8\"?>';
    soap += '<soap:Envelope xmlns:xsi="\http://www.w3.org/2001/XMLSchema-instance\" 
        xmlns:xsd="\http://www.w3.org/2001/XMLSchema\"
        xmlns:soap="\http://schemas.xmlsoap.org/soap/envelope/\">';
    soap += '<soap:Body>';
    soap += '<UpdateListItems xmlns="%22">http://schemas.microsoft.com/sharepoint/soap/">';
    soap += '<listName>{5F4BA3A8-EA8B-41D2-95E6-461D69A5D455}</listName>'      
    soap +=   '<updates><Batch>'  
    soap += '<Method ID="1" Cmd="New"><Field Name="Title">'+ Title +'</Field>;
    soap += ' </Method></Batch></updates>'    
    soap += '</UpdateListItems></soap:Body></soap:Envelope>'; 
  
    return soap; }

The Listname in createEnvelope is the list guid and the Field Name would be the internal name\id of the field.

You can open up the lists.asmx webservice in your browser to see more functions. for eg, GetlistItems to query or return all the items in the list and lot more.

for more function please see my blog post at

http://mysharepointwork.blogspot.com/2009/10/sharepoint-webservices-examples.html

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)