Get SharePoint list items using SPServices

SharePoint list items & CRUD operations using spservices

SP Services is the best programming concept for the MOSS 2007, SharePoint 2010 & SharePoint 2013 as well.

The developers who are not having the knowledge on SharePoint Server Object Model(SSOM) or SharePoint Client Object Model(CSOM) can work with this SP Services. It is the best option to them and even PHP developers and other web developers also can work who are having Javascript knowledge.

It is developed by the codeplex open source community.

In order to work with SP Services we should have JQuery also in our SharePoint Page. Because SP Services is developed using jquery.

In order to work with SP Services need to be downloaded below two references.

  1. Jquery
  2. SP Services reference

Once downloaded the above files, please go though the below steps.

Here, I have used SCHOOL list for the sample. The below is the screen shot

imgSchoolList

  1. Open your SharePoint site in SharePoint designer
  2. Go to SitePages and create sample *.aspx page
  3. Go to SiteAssets and create sample *.js file
  4. Edit page in Advanced mode as shown in image.

     imgEditAdvancedMode

  5. Add reference in header as below
    <head runat="server">
    <meta name="WebPartPageExpansion" content="full" />
    <meta http-equiv="X-UA-Compatible" content="IE=10" />
    <SharePoint:CssRegistration Name="default" runat="server"/>
    <!-- JQuery Reference-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <!-- SP Service Reference-->
    <script type="text/javascript" src="../SiteAssets/jquery.SPServices-2014.02.min.js"></script>
    <!-- Custom code reference -->
    <script type="text/javascript" src="../SiteAssets/spservice.js"></script>
    </head>
    
  6. Now the sample page is included with the SP Services reference
  7. To display the list content we need to have one substitute control, so that I have created div(divContent) and input contrls for the CUD operations.
    <body>
    Welcome to the sharepoint SP Services
    <div id="divContent"></div>
    <div>
       <table>
          <tr>
             <td>Name:</td>
             <td><input type="text" id="txtName"/></td>
          </tr>
          <tr>
             <td>Marks:</td>
             <td><input type="text" id="txtMarks"/></td>
          </tr>
          <tr>
             <td></td>
             <td><input type="button" id="btnAdd" value="Add" onclick="addItem()"/></td>
          </tr>
       </table>
    </div>
    <div>
       <table>
          <tr>
             <td>ID:</td>
             <td><input type="text" id="txtid"/></td>
          </tr>
          <tr>
             <td></td>
             <td><input type="button" id="btnAdd" value="Update" onclick="itmUpdate()"/>&nbsp;<input type="button" id="btnAdd" value="Delete" onclick="itemDelete()"/></td>
          </tr>
       </table>
    </div>
    </body>
    
  8. Open *.js file in SiteAssets and write the below code
    $(document).ready(function () {
    	$.ajax({
    		success : function () {
    			loadContent();
    		}
    	});
    });
    
    //To display all items from SCHOOL list
    function loadContent() {
    	var myJson = [];
    	$().SPServices({
    		operation : "GetListItems", //Method name
    		async : false,
    		//webURL : webUrl,//pass webUrl dynamically
    		listName : "SCHOOL", // List Name
    		//CAMLQueryOptions : "",
    		//CAMLViewFields : "<ViewFields><FieldRef Name='Title' /></ViewFields>",
    		//CAMLQuery : "",
    		//CAMLRowLimit : 1,
    		completefunc : function (xData, Status) {
    			//alert(xData.responseText);
    			if (xData.status == 200) {
    				//debugger;
    				myJson = $(xData.responseXML).SPFilterNode("z:row").SPXmlToJson({
    						mapping : {
    							ows_ID : {
    								mappedName : "ID",
    								objectType : "Counter"
    							},
    							ows_Title : {
    								mappedName : "Title",
    								objectType : "Text"
    							},
    							ows_Marks : {
    								mappedName : "marks",
    								objectType : "Number"
    							}
    						}, // name, mappedName, objectType
    						includeAllAttrs : true
    					});
    				//alert(myJson);
    			} else {
    				alert(xData.status);
    			}
    		}
    	});
    
    	//debugger;
    	//JSON Viewer
    	//http://jsonviewer.stack.hu/
    	var listItemInfo = '<table>';
    	for (var i = 0; i < myJson.length; i++) {
    		listItemInfo += "<tr>";
    		listItemInfo += "<td>" + myJson[i].ID + "</td>";
    		listItemInfo += "<td>" + myJson[i].Title + "</td>";
    		listItemInfo += "<td>" + myJson[i].marks + "</td>";
    		listItemInfo += "</tr>";
    	}
    	listItemInfo += "</table>";
    	$('#divContent').html(listItemInfo);
    }
    
    function addItem() {
    	var strName = $('#txtName').val();
    	var strMarks = $('#txtMarks').val();
    	alert(strName);
    
    	$().SPServices({
    		operation : "UpdateListItems",
    		async : false,
    		batchCmd : "Update",
    		listName : "SCHOOL",
    		updates : "<Batch OnError='Continue' PreCalc='TRUE' >"
    		 + "<Method ID='1' Cmd='New'>"
    		 + "<Field Name='Title' >" + strName + "</Field>"
    		 + "<Field Name='Marks' >" + strMarks + "</Field>"
    		 + "</Method></Batch>",
    		completefunc : function (xData, Status) {
    			if (xData.status == 200) {
    				//alert('File added successfully');
    			} else {
    				alert(xData.responseXML.xml);
    			}
    		}
    	});
    	loadContent();
    }
    
    //To update the item
    function itmUpdate() {
    	var strName = $('#txtName').val();
    	var strMarks = $('#txtMarks').val();
    
    	var strid = $('#txtid').val();
    
    	$().SPServices({
    		operation : "UpdateListItems",
    		async : false,
    		batchCmd : "Update",
    		listName : "SCHOOL",
    		updates : "<Batch OnError='Continue' PreCalc='TRUE' >"
    		 + "<Method ID='1' Cmd='Update'>"
    		 + "<Field Name='ID'>" + strid + "</Field>"
    		 + "<Field Name='Title'>" + strName + "</Field>"
    		 + "<Field Name='Marks'>" + strMarks + "</Field>"
    		 + "</Method></Batch>",
    		completefunc : function (xData, Status) {
    			if (xData.status == 200) {
    				alert('File updated successfully');
    			} else {
    				alert(xData.responseXML.xml);
    			}
    		}
    	});
    
    	loadContent();
    }
    
    //To delete the item
    function itemDelete() {
    	var strid = $('#txtid').val();
    	$().SPServices.SPUpdateMultipleListItems({
    		listName : "SCHOOL",
    		CAMLQuery : "<Query><Where><Eq><FieldRef Name='ID'/><Value Type='Text'>" + strid + "</Value></Eq></Where></Query>",
    		batchCmd : "Delete",
    		completefunc : function (xData, Status) {
    			if (xData.status == 200) {
    				alert('Deleted Successfully');
    			}
    		}
    	});
    	loadContent();
    }
    
  9. Out put will be like below
    imgDisplay

The below are the operation:

ADD :

  1. Fill the values (Name, Marks) into the text boxes and click on ‘Add’

UPDATE:

  1. Enter ID:
  2. Fill the values (Name, Marks) into the text boxes and click on Update

DELETE:

  1. Enter ID:
  2. Fill the values (Name, Marks) into the text boxes and click on Update

I hope you enjoy.

Read More

SharePoint ECMA example

Here in this article I am going to explain how to write the code using ECMA.

1. Open your SharePoint site
2. Create a list “SCHOOL” using custom list template
3. Create a column “Marks” with the Number field type, Add few sample records/items
4. Open the site in SharePoint Designer
4. Add an *.aspx page with the SharePoint default master page
5. Add the below code into the contentplaceholderid=PlaceHolderMain of the *.aspx page


<!-- BELOW USE YOUR Javascript FILES INSTEAD THE BELOW FILES -->
<script type="text/javascript" src="http://dc01:8888/SiteAssets/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="http://dc01:8888/SiteAssets/main.js"> </script>
  
   
<div id="divdisplay">
Program error..!
</div>

<table>
<tr><th colspan="2"></th></tr>
<tr><td>Name:</td><td><input id="txtName" type="text"/></td></tr>
<tr><td>Marks:</td><td><input id="txtMarks" type="text"/></td></tr>
<tr><td colspan="2" align="right">
<input type="button" value="Create" onclick="createItem()"/>
</td></tr>
</table>
To update or delete the item first enter the item id in to below text box and click.
<table>
<tr><td colspan="2"><input id="txtid" type="text"/></td></tr>
<tr><td colspan="2">
<input type="button" value="Update" onclick="updateItem()"/>
<input type="button" value="Delete" onclick="deleteItem()"/>
</td></tr>

</table>

6. Once done with the design page, Please open the *.js file and add the below code in to the Javascript file


var context = "";
var web = "";
var list = "";
var item = "";
var lists = "";
var collListItem = "";

$(document).ready(function () {
	ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");
});

function RetrieveListItems() {
	debugger;
	context = new SP.ClientContext.get_current();
	web = context.get_web();

	lists = web.get_lists();

	list = web.get_lists().getByTitle('SCHOOL');


	context.load(this.web);
	context.load(this.lists);
	context.load(this.list);

	context.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFailure));
}

function onSuccess() {
	//debugger
	context.load(list);
	var itemsCount = list.get_itemCount();
	//if you are not passing any CAML query then have to use createAllItemsQuery()
	var camlQuery = new SP.CamlQuery.createAllItemsQuery();
	//var camlQuery = new SP.CamlQuery();
	//camlQuery.set_viewXml('<View><Query><Where><Gt><FieldRef Name="Marks" /><Value Type="Number">40</Value></Gt></Where></Query></View>');
	collListItem = list.getItems(camlQuery);
	context.load(collListItem);
	context.executeQueryAsync(Function.createDelegate(this, this.viewItems), Function.createDelegate(this, this.onFailure));
}

function viewItems() {
	var listItemInfo = '<table>';

	var listItemEnumerator = collListItem.getEnumerator();
	
	while (listItemEnumerator.moveNext()) {
		var oListItem = listItemEnumerator.get_current();

		listItemInfo += "<tr>";
		listItemInfo += "<td>" + oListItem.get_id() + "</td>";
		listItemInfo += "<td>" + oListItem.get_item('Title') + "</td>";
		listItemInfo += "<td>" + oListItem.get_item('Marks') + "</td>";
		listItemInfo += "</tr>";
	}
	listItemInfo += "</table>";
	document.getElementById('divdisplay').innerHTML = listItemInfo;
}

function onFailure(sender, args) {
	alert('Request failed.' + args.get_message() + ' \n' + args.get_stackTrace());
}


function createItem() {
	//alert("Working");
	var strName = document.getElementById("txtName").value;
	var strMarks = document.getElementById("txtMarks").value;

	var itemCreateInfo = new SP.ListItemCreationInformation();
	this.item = this.list.addItem(itemCreateInfo);


	item.set_item('Title', strName);
	item.set_item('Marks', strMarks);

	item.update();
	context.load(item);
	
	context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onFailure));
}

function onQuerySucceeded() {
	
	$('#txtName').val('');
	$('#txtMarks').val('');
	onSuccess();
}

function updateItem() {
	
	var strName = document.getElementById("txtName").value;
	var strMarks = document.getElementById("txtMarks").value;

	var strid = document.getElementById("txtid").value;
	this.item = this.list.getItemById(strid);

	item.set_item('Title', strName);
	item.set_item('Marks', strMarks);

	item.update();
	context.load(item);
	context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onFailure));
}


function deleteItem()
{
	var strid = document.getElementById("txtid").value;
	this.item = this.list.getItemById(strid);
    item.deleteObject();
	context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onFailure));
}

7. Now run the *.aspx page.

If any errors occur please post comment.

Read More