Microsoft SharePoint and .NET Technology Insight

SharePoint, .NET, Office365, Windows Azure, TFS, Project Server and SQL Server Technology Insights


Leave a comment

Dynamically updating URL links within a SharePoint 2010 Content Editor Web-Part (CEWP) and reading the values from a SharePoint list using JQuery

Here is an example of dynamically updating URL links within a SharePoint 2010 Content Editor Web-Part (CEWP) and reading the values from a SharePoint list using JQuery:


<script type="text/javascript">

function processResult(xData, status) {
$(xData.responseXML).find("z\\:row").each(function() {

var keyResources1 = $("#KeyResourcesMain");
var url = $(this).attr("ows_LinkUrl");
var htmlTimeSheet = "<li><a href = " + url + ">My TimeSheet</a></li>";

keyResources1.append(html);
keyResources1.append(htmlTimeSheet);

});
}

$(document).ready(function() {
var soapEnv = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'><soapenv:Body><GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'><listName>Popular Links</listName><query><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>My Timesheet</Value></Eq></Where></Query></query><viewFields><ViewFields><FieldRef Name='LinkUrl' /><FieldRef Name='Title' /></ViewFields></viewFields></GetListItems></soapenv:Body></soapenv:Envelope>";
$.ajax({
url: "/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
complete: processResult,
contentType: "text/xml; charset=\"utf-8\""
});
});

</script>

<div><h3>Key Resources</h3>
<ul id="KeyResourcesMain"></ul>
</div>

The above approach of using the JQuery Document.Ready Function is better when compared to using the JavaScript _spBodyOnLoadFunctionNames and loads a custom user defined Javascript during rendering of a page instead of loading the Custom JavaScript after rendering of the page is completed.

The functions in _spBodyOnLoadFunctionNames run after the page is finished rendering by definition. In SharePoint 2010, this effect may be more visible since in SharePoint 20010 there is more Out of box JavaScript that runs during page load. You could try to accomplish UI updates (for example updating URLs in a CEWP from SharePoint Lists as in the above example) using the server-side APIs (e.g. content placeholders, delegate controls) or using JQuery and running your script on document ready instead of waiting for the page to call the customr script after other SharePoint 2010 out of box Javascript code on is done loading on the page.