Friday 30 August 2013

Read SharePoint 2010 list data using jQuery

In this article we will discuss on how to read SharePoint 2010 list data using jQuery. Also you can check my previous posts on: Get user profile properties in SharePoint 2013Upload file to document library using SharePoint 2010 obect model and Programmatically get SharePoint Themes.

Here we are going to write all the code in a content editor webpart.

First we need to use 2 js files name as: jquery.min.js and jquery.SPServices.min.js.

Below is the full code to read data from SharePoint 2010 list using jQuery.

Here the list name is MyCustomList and the columns we are going to read are Title, Description and Created.

$(document).ready(function() { 
    GetListItems();
});

function GetListItems()
{
var method = "GetListItems";
var list = "MyCustomList";
var fieldsToRead =     "<ViewFields>" +
                                "<FieldRef Name='Title' />" +
                                "<FieldRef Name='Description' />" +
                                "<FieldRef Name='Created' />" +
                            "</ViewFields>";
var query = "<Query>" +
                        "<Where>" +
                            "<Neq>" +
                                "<FieldRef Name='ID'/><Value Type='Number'>0</Value>" + 
                            "</Neq>" +
                        "</Where>" +
                        "<OrderBy>" + 
                            "<FieldRef Name='Created' Ascending='False' />" +
                        "</OrderBy>" +
                    "</Query>";

 $().SPServices({
                operation: method,
                async: false,  //if you set this to true, you may get faster performance, but your order may not be accurate.
                listName: list,
                CAMLViewFields: fieldsToRead,
                  CAMLQuery: query,
                      //this basically means "do the following code when the call is complete"
                    completefunc: function (xData, Status) { 
                        //this code iterates through every row of data returned from the web service call
                        $(xData.responseXML).SPFilterNode("z:row").each(function() 

var name = ($(this).attr("ows_Title"));

var Description = ($(this).attr("ows_Description"));
var Created = ($(this).attr("ows_Created"));

 AddRowToTable(name,Description,Created);
                            
                        });                
                    }
        });

}


function AddRowToTable(name,Description,Created)
{
    $("#MyTable").append("<tr align='left'>" + 
                                "<td><a href='" + name+ "'>" + Description+ "</a><br><a href='" + name+ "'>" + Created+ "</a></td>" +
                               "</tr>");
                                
}</script>

<table id="MyTable"></table>

No comments:

Post a Comment