Search This Blog

Friday, September 9, 2016

SharePoint 2013 Dynamically Adding Dropdown Using REST API and jQuery

REST Services-High Level Overview:
Let's start out with our basic get commands in REST. The following is a list of the basic commands used to get List Items from a SharePoint List using the SharePoint 2013 REST Services.


Imagine

In my example, I'm accessing a Custom list (of countries) and output the result binding it to a dynamic dropdown. I have sorted by a column in ascending only. Using SharePoint's REST API lets us add these filters to our request. The results are given to us as a JSON object that we can then loop through and insert into a dropdown runtime. I also used a modular pattern to structure my code. We can generate our REST request. _spPageContextInfo is a SharePoint object that gives us useful information about the page and site we're on, including the base URL of our site.

After successfully getting our list information, we just need to loop through our data, put it in a dropdown and then inserted into our predefined container element. jQuery helps make this an easy process.


Let's proceed.

Step 1: Navigate to your SharePoint 2013 site.

Step 2: From this page select the Site Actions | Edit Page.

Edit the page, go to the "Insert" tab in the Ribbon and click the "Web Part" option. In the "Web Parts" picker area, go to the "Media and Content" category, select the "Script Editor" Web Part and press the "Add button".

Step 3: Once the Web Part is inserted into the page, you will see an "EDIT SNIPPET" link; click it. You can insert the HTML and/or JavaScript as in the following:

  1. <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>  
  2. <script>  
  3.   
  4.     $(document).ready(function () {  
  5.         countriesDrpDownBind();  
  6.       });  
  7.     function countriesDrpDownBind() {  
  8.         var listName = "countries";  
  9.         var url = _spPageContextInfo.webAbsoluteUrl;  
  10.   
  11.         getListItems(listName, url, function (data) {  
  12.             var items = data.d.results;  
  13.              
  14.             var inputElement = '<select id="drpcountries"> <option  value="">Select</option>';  
  15.                // Add all the new items  
  16.             for (var i = 0; i < items.length; i++) {  
  17.                  var itemId = items[i].Title,  
  18.                    itemVal = items[i].Title;  
  19.                  inputElement += '<option value="' + itemId + '"selected>' + itemId + '</option>';  
  20.                 
  21.                }  
  22.                 inputElement += '</select>';  
  23.                 $('#divisiondrp').append(inputElement);  
  24.   
  25.               $("#drpcountries").each(function () {  
  26.                 $('option'this).each(function () {  
  27.   
  28.                     if ($(this).text() == 'Select') {  
  29.                         $(this).attr('selected''selected')  
  30.                     };  
  31.                 });  
  32.             });  
  33.                // assign the change event to provide an alert of the selected option value  
  34.               $('#drpcountries').on('change'function () {  
  35.               alert($(this).val());  
  36.                   });  
  37.              
  38.           }, function (data) {  
  39.             alert("Ooops, an error occured. Please try again");  
  40.         });  
  41.     }  
  42.     // READ operation  
  43.     // listName: The name of the list you want to get items from  
  44.     // siteurl: The url of the site that the list is in.  
  45.     // success: The function to execute if the call is sucesfull  
  46.     // failure: The function to execute if the call fails  
  47.     function getListItems(listName, siteurl, success, failure) {  
  48.         $.ajax({  
  49.             url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$orderby=Title asc",  
  50.             method: "GET",  
  51.             headers: { "Accept""application/json; odata=verbose" },  
  52.             success: function (data) {  
  53.                 success(data);  
  54.             },  
  55.             error: function (data) {  
  56.                 failure(data);  
  57.             }  
  58.         });  
  59.     }  
  60.   
  61. </script>  
  62. Division  
<div id="divisiondrp"></div>

Finally the result looks as in the following:


CRUD On List Items Using Web Services and jQuery In SharePoint 2013

Now, I will demo all the operations on list items including retrieve, create, update and delete onlist items.

Retrieve the list items:

  1. function retriveListItem()  
  2. {  
  3.     var soapEnv = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \  
  4. <soapenv:Body> \  
  5. <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \  
  6. <listName>companyInfo</listName> \  
  7. <viewFields> \  
  8. <ViewFields> \  
  9. <FieldRef Name='Company' /> \  
  10. <FieldRef Name='Industry' /> \  
  11. </ViewFields> \  
  12. </viewFields> \  
  13. </GetListItems> \  
  14. </soapenv:Body> \  
  15. </soapenv:Envelope>";  
  16.     $.ajax(  
  17.     {  
  18.         url: _spPageContextInfo.webAbsoluteUrl + "/apps/_vti_bin/Lists.asmx",  
  19.         type: "POST",  
  20.         dataType: "xml",  
  21.         data: soapEnv,  
  22.         complete: processResult,  
  23.         contentType: "text/xml; charset=\"utf-8\""  
  24.     });  
  25. }  
  26.   
  27. function processResult(xData, status)  
  28. {  
  29.     var MainResult = "";  
  30.     $(xData.responseXML).find("z\\:row").each(function()  
  31.     {  
  32.         var companyName = $(this).attr("ows_Company");  
  33.         var Industry = $(this).attr("ows_Industry");  
  34.         MainResult += MainResult + companyName + "-" + Industry + "\n";  
  35.     });  
  36.     $('#ResultDiv').text(MainResult);  
  37. }  
Create list item:
Here is the main code in detail:

  1. function createListItem() {  
  2.     var batch =  
  3.         "<Batch OnError=\"Continue\"> \  
  4.     <Method ID=\"1\" Cmd=\"New\"> \  
  5.         <Field Name=\"Company\">" + $("#Company").val() + "</Field> \  
  6.          <Field Name=\"Industry\">" + $("#Industry").val() + "</Field> \  
  7.               </Method> \  
  8. ch>";  
  9.   
  10.     var soapEnv =  
  11.         "<?xml version=\"1.0\" encoding=\"utf-8\"?> \  
  12. <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \  
  13.     xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \  
  14.     xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> \  
  15.   <soap:Body> \  
  16.     <UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\"> \  
  17.       <listName>companyInfo</listName> \  
  18.       <updates> \  
  19.         " + batch + "</updates> \  
  20.     </UpdateListItems> \  
  21.   </soap:Body> \  
  22. </soap:Envelope>";  
  23.   
  24.     $.ajax({  
  25.         url: _spPageContextInfo.webAbsoluteUrl+ "/apps/_vti_bin/Lists.asmx",  
  26.         beforeSend: function(xhr) {  
  27.             xhr.setRequestHeader("SOAPAction",  
  28.             "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");  
  29.         },  
  30.         type: "POST",  
  31.         dataType: "xml",  
  32.         data: soapEnv,  
  33.         complete: processResult,  
  34.         contentType: "text/xml; charset=utf-8"  
  35.     });  
  36. }  
  37.   
  38. function processResult(xData, status) {  
  39.     retriveListItem();  
  40. }  

Update list item:
Here is the main code in detail:
  1. function updateListItem() {  
  2.       
  3.     var UpdateNewItemXml =  
  4.         "<Batch OnError=\"Continue\"> \  
  5.     <Method ID=\"1\" Cmd=\"Update\"> \  
  6.         <Field Name=\"ID\">7</Field>\  
  7.          <Field Name=\"Industry\">" + $("#Industry").val() + "</Field> \  
  8.               </Method> \</Batch>";  
  9.    var soapEnv =  
  10.         "<?xml version=\"1.0\" encoding=\"utf-8\"?> \  
  11. <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \  
  12.     xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \  
  13.     xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> \  
  14.   <soap:Body> \  
  15.     <UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\"> \  
  16.       <listName>companyInfo</listName> \  
  17.       <updates> \  
  18.         " + UpdateNewItemXml + "</updates> \  
  19.     </UpdateListItems> \  
  20.   </soap:Body> \  
  21. </soap:Envelope>";  
  22.   
  23.     $.ajax({  
  24.         url: _spPageContextInfo.webAbsoluteUrl + "/apps/_vti_bin/Lists.asmx",  
  25.         beforeSend: function (xhr) {  
  26.             xhr.setRequestHeader("SOAPAction",  
  27.             "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");  
  28.         },  
  29.         type: "POST",  
  30.         dataType: "xml",  
  31.         data: soapEnv,  
  32.         complete: processResult,  
  33.         contentType: "text/xml; charset=utf-8"  
  34.     });  
  35. }  
  36. function processResult(xData, status) {  
  37.     retriveListItem();  
}

Delete list item:
here is the main code in detail:
  1. function deleteListItem()  
  2. {  
  3.     var DeleteItemXml = "<Batch OnError=\"Continue\"> \  
  4.             <Method ID=\"1\" Cmd=\"Delete\"> \  
  5.                 <Field Name=\"ID\">7</Field>\  
  6.                 <Field Name=\"Company\">" + $("#Company").val() + "</Field> \  
  7.                       </Method> \</Batch>";  
  8.     var soapEnv = "<?xml version=\"1.0\" encoding=\"utf-8\"?> \  
  9.         <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \  
  10.             xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \  
  11.             xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> \  
  12.           <soap:Body> \  
  13.             <UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\"> \  
  14.               <listName>companyInfo</listName> \  
  15.               <updates> \  
  16.                 " + DeleteItemXml + "</updates> \  
  17.             </UpdateListItems> \  
  18.           </soap:Body> \  
  19.         </soap:Envelope>";  
  20.     $.ajax(  
  21.     {  
  22.         url: _spPageContextInfo.webAbsoluteUrl + "/apps/_vti_bin/Lists.asmx",  
  23.         beforeSend: function(xhr)  
  24.         {  
  25.             xhr.setRequestHeader("SOAPAction""http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");  
  26.         },  
  27.         type: "POST",  
  28.         dataType: "xml",  
  29.         data: soapEnv,  
  30.         complete: processResult,  
  31.         contentType: "text/xml; charset=utf-8"  
  32.     });  
  33. }  
  34.   
  35. function processResult(xData, status)  
  36. {  
  37.     retriveListItem();  
}