Display sharepoint list data to dynamic html table using jQuery - sharepoint

I am having a scenario where i need to get the list data to be shown in dynamic html table using jQuery to display in site with content editor webpart. Please help me out with this regards thanks in advance...

You can use SharePoint Client Context REST API to get the data and display it in a table. Add reference to these three scripts:
1. /_layouts/15/SP.Runtime.js
2./_layouts/15/SP.js
3. //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
And use below example:
<script type="text/javascript">
$(document).ready(function () {
fnGetData();
});
function fnGetData() {
context = new SP.ClientContext.get_current();
web = context.get_web();
var list = web.get_lists().getByTitle('Users');
var myquery = new SP.CamlQuery();
myquery.set_viewXml("<View><Query>" +
"<Where>" +
"<IsNotNull>" +
"<FieldRef Name='Title' />" +
"</IsNotNull>" +
"</Where>" +
"</Query></View>");
myquery.set_datesInUtc(false);
myItems = list.getItems(myquery);
context.load(myItems);
context.executeQueryAsync(Function.createDelegate(this, function () { fnGetDataSuccess(); }), Function.createDelegate(this, this.fnGetDataFailed));
}
function fnGetDataSuccess() {
var txtHTML = "";
var ListEnumeratorAcc = this.myItems.getEnumerator();
while (ListEnumeratorAcc.moveNext()) {
var currentItem = ListEnumeratorAcc.get_current();
txtHTML = txtHTML + "<tr>";
txtHTML = txtHTML + "<td>";
if (currentItem.get_item('Title') != null) {
txtHTML = txtHTML + currentItem.get_item('Title');
}
txtHTML = txtHTML + "</td>";
txtHTML = txtHTML + "<td>";
if (currentItem.get_item('Owner') != null) {
txtHTML = txtHTML + currentItem.get_item('Owner').get_lookupValue();
}
txtHTML = txtHTML + "</td>";
txtHTML = txtHTML + "</tr>";
}
$("#tblCustomListData").append(txtHTML);
}
function fnGetDataFailed(sender, args) {
alert("Error Message:\n" + "URL: " + sender.get_url() + ". \n\Error Description:" + args.get_message());
}
</script>
<table id="tblCustomListData" border="1">
<thead>
<tr>
<th>Title
</th>
<th>Owner
</th>
</tr>
</thead>
</table>

You can either use SharepointPlus or SPServices to retrieve the list data. Then it's easy to use jQuery to insert the data into the HTML page.

Related

Sharepoint 2013 - Fetch last modified date of the list

Trying to fetch the last modified time of Sharepoint list. Found a code that states the author and modified by. It was working fine when it had the line
<input id="btnGetFieldUserValue" onclick="getFieldUserValue()" type="button" value="Get Created by and Modified by"/>
but when i changed to
<div id="create" onload="getFieldUserValue()">  </div>
No repose in the content editor webpart of sharepoint 2013.
Help.
My task is to show the last updation time of the list. Any other way to do that, please share.
var listItem;
var list;
var clientContext;
function getFieldUserValue() {
this.clientContext = SP.ClientContext.get_current();
if (this.clientContext != undefined && clientContext != null) {
var webSite = clientContext.get_web();
this.list = webSite.get_lists().getByTitle("Resource Readiness");
this.listItem = list.getItemById(1);
clientContext.load(this.listItem);
this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
}
}
function OnLoadSuccess(sender, args) {
var fieldUserValueCreatedBy = this.listItem.get_item("Author");
var fieldUserValueModifiedBy = this.listItem.get_item("Editor");
document.getElementById("create").innerHTML = fieldUserValueModifiedBy.get_lookupValue() ;
alert("Created By: " + fieldUserValueModifiedBy.get_lookupValue() + "\n Modified By: " + fieldUserValueModifiedBy.get_lookupValue() + "\n");
}
function OnLoadFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}</script>
 
You have to wait for script files:
function getFieldUserValue(){
SP.SOD.executeOrDelayUntilScriptLoaded(loadContext, 'sp.js');
}
function loadContext() {
this.clientContext = SP.ClientContext.get_current();
if (this.clientContext != undefined && clientContext != null) {
var webSite = clientContext.get_web();
this.list = webSite.get_lists().getByTitle("Resource Readiness");
this.listItem = list.getItemById(1);
clientContext.load(this.listItem);
this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
}
}
function OnLoadSuccess(sender, args) {
var fieldUserValueCreatedBy = this.listItem.get_item("Author");
var fieldUserValueModifiedBy = this.listItem.get_item("Editor");
document.getElementById("create").innerHTML = fieldUserValueModifiedBy.get_lookupValue() ;
alert("Created By: " + fieldUserValueModifiedBy.get_lookupValue() + "\n Modified By: " + fieldUserValueModifiedBy.get_lookupValue() + "\n");
}
function OnLoadFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

i want display list in sharepoint 2013 uses js

Following is my code:
retrieveListItems('https://sustec29-public.sharepoint.com');
function retrieveListItems(siteUrl) {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
'<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
'<Value Type=\'Number\'>1</Value></Geq></Where></Query>' +
'<RowLimit>10</RowLimit></View>'
);
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '\nID: ' + oListItem.get_id() +
'\ngroup: ' + oListItem.get_item('group') +
'\ndisc: ' + oListItem.get_item('disc');
}
$('#message').text(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
`
but browser views error -
The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
if i write
'\ntitle: ' + oListItem.get_item('title') + '\nbody: ' + oListItem.get_item('body');
and rename field table`s - all ok.
But i want add own field..
Try to add ViewFields section to your caml query:
camlQuery.set_viewXml(
'<View><Query><Where><Geq><FieldRef Name="ID"/>' +
'<Value Type="Number">1</Value></Geq></Where></Query>' +
'<RowLimit>10</RowLimit><ViewFields><FieldRef Name="group" /><FieldRef Name="disk" /></ViewFields></View>'
EDIT:
Another way you can try to achieve this is to add Include string to your load method call:
clientContext.load(collListItem, 'Include(Id, disk, group)');

jquery dynamically create html table and bind sharepoint list items in it

I have scenario where i need to bind sharepoint list to the dynamically cretaed html table and use the jquery in content editor webpart to show the table in site.Please help me with this regards.I am using sharepoint 2010.Thanks in advance.
I was trying something here but no luck please help me around with this.Thanksenter code here
<script type="text/javascript" language="javascript">
var _clientContext;
var _web;
alert("Working")
//ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");
function RetrieveListItems() {
alert("Test");
_clientContext = new SP.ClientContext.get_current();
alert(Context);
_web = _clientContext.get_web();
alert(web);
var list = _web.get_lists().getByTitle('Planning Partners');
alert(list);
// var camlQuery = new SP.CamlQuery();
var myquery = new SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(myquery);
_clientContext.load(allItems);
_clientContext.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var Image = null;
var Linkurl = null;
var Title = null;
// var sHtml = "";
alert("success");
var ListEnumerator = this.allItems.getEnumerator();
while (ListEnumerator.moveNext()) {
var currentItem = ListEnumerator.get_current();
Image = currentItem.get_item('Image');
Linkurl = currentItem.get_item('Linkurl');
Title = currentItem.get_item('Title');
//var tbl = document.createElement("tbl");
var row = document.createElement("tr");
var $table = $('<table>');
$table.append('<caption>MyTable</caption>')
$table.append('<thead>');
$table.append('<tr>');
if (Image != oListItem.get_item('Image')) {
var cell = document.createElement("td");
var cellText = document.createElement("<image imgurl='" + oListItem.get_item('Image') + "'></Image>");
cell.appendChild(cellText);
row.appendChild(cell);
}
if (Linkurl != oListItem.get_item('Linkurl')) {
var cell = document.createElement("td");
var cellText = document.createElement("<a target='_blank' href ='" + oListItem.get_item('Linkurl') + "'>" + oListItem.get_item('Title') + "</a>");
cell.appendChild(cellText);
row.appendChild(cell);
}
if (Title != oListItem.get_item('Title')) {
var cell = document.createElement("td");
var cellText = document.createElement("<p>" + Title + "</p>");
cell.appendChild(cellText);
row.appendChild(cell);
}
$table.append('</tr>');
$table.append('</thead>');
tblBody.appendChild(row);
tbl.appendChild(tblBody);
body.appendchild(tbl);
}
}
// sHtml += '<table><tr><td><img src="' + Image + '" height="55px" width="55px"></td><td><table><tr><td valign="top"><div class="fieldsTitle">' + Linkurl + '</div></td></tr><tr><td valign="top">' + Title + 'Read More >></td></tr><tr><td></td></tr></table></td></tr></table>';
// document.getElementById('MainDiv').innerHTML = sHtml;
// }
function failed(sender, args) {
alert("failed Message" + args.gte_message());
}
</script>
Instead of creating elements through JavaScript, simply create a variable to store theHTML tags and finally add on page using Jquery. Use below script, hope this will help you.
If "Image" and "Linkurl" are HyperLink or Picture Column then use currentItem.get_item('Image').get_url() . I think this was the issue in your case :)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js "></script>
<script type="text/javascript" language="javascript">
var _clientContext;
var _web;
ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");
function RetrieveListItems() {
_clientContext = new SP.ClientContext.get_current();
_web = _clientContext.get_web();
var list = _web.get_lists().getByTitle('Planning Partners');
var myquery = new SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(myquery);
_clientContext.load(allItems);
_clientContext.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var Image = null;
var Linkurl = null;
var Title = null;
var txtHTML = "";
var ListEnumerator = this.allItems.getEnumerator();
while (ListEnumerator.moveNext()) {
var currentItem = ListEnumerator.get_current();
Image = currentItem.get_item('Image');
Linkurl = currentItem.get_item('Linkurl');
Title = currentItem.get_item('Title');
var row = document.createElement("tr");
txtHTML = txtHTML + "<tr>";
txtHTML = txtHTML + "<td>";
if (Image != null) {
txtHTML = txtHTML + "<image src='" + Image.get_url() + "'></Image>";
}
txtHTML = txtHTML + "</td>";
txtHTML = txtHTML + "<td>";
if (Linkurl != null) {
txtHTML = txtHTML + "<a target='_blank' href ='" + Linkurl.get_url() + "'>" + Title + "</a>";
}
txtHTML = txtHTML + "</td>";
txtHTML = txtHTML + "<td>";
if (Title != null) {
txtHTML = txtHTML + "<p>" + Title + "</p>";
}
txtHTML = txtHTML + "</td>";
txtHTML = txtHTML + "</tr>";
}
$("#tblCustomListData").append(txtHTML);
}
function failed(sender, args) {
alert("failed Message" + args.gte_message());
}
</script>
<table id="tblCustomListData" border="1">
<thead>
<tr>
<th>Image
</th>
<th>Linkurl
</th>
<th>Title
</th>
</tr>
</thead>
</table>

Item Selection with PDF Preview

I need to make a Page with a Listbox (DropDown) with all Files from a Library and then a PDF Preview.
I made a Page with a HTML Form Web Part. The Preview can be made like this:
<embed height="800" width="1200" src="..." type="application/pdf">
How can I provide now a Listbox with all Items from the Library and change the source from the to the selected Item?
Okay I got it..
I made a new Page with a HTML Form Web Part, and got this with Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
var siteUrl = '/XX';
var listName = 'YY';
var listItems;
function retrieveAllListProperties() {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle(listName);
var query = new SP.CamlQuery();
query.set_viewXml("<View Scope='RecursiveAll'><Query><OrderBy><FieldRef Name='FileLeafRef' Ascending='True' /></OrderBy></Query></View>");
listItems = oList.getItems(query);
clientContext.load(listItems);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
var listEnumerator = listItems.getEnumerator();
$('#select').find('option').remove().end().append('<option value="">Please select</option>');
while (listEnumerator.moveNext()) {
var listItem = listEnumerator.get_current();
$('#select').append('<option value="http://host' + listItem.get_item('FileRef') + '">' + listItem.get_item('FileLeafRef') + '</option>');
}
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
$(this).ready(function() {
ExecuteOrDelayUntilScriptLoaded(retrieveAllListProperties, "sp.js");
$('#etiketten').change(function() {
$('#pdf').remove();
if($('#select').val() != '') {
$('#container').append('<embed name="pdf" id="pdf" height="768" width="1024" src="' + $('#select').val() + '" type="application/pdf">');
}
});
});
</script>
<div id="container" name="container">
<select name="select" id="select">
<option value="">Please select</option>
</select>
<br/>
</div>

How to make a Sharepoint Survey window open on page load

I've been working on looking for an answer to this issue for several days. I've created a survey on a Sharepoint 2010 site, and the person who I made it for wants it to open in a modal window on page load, instead of having to click "Respond to Survey" for this to happen.
I've tried multiple javascript based solutions, and so far I've gotten nothing. Is there any way to do this? And, if there is, is it possible that this solution could be ported to other pages, so that I can make other surveys or other sharepoint pages open in a modal window (on page load) instead of on a separate page?
Use .../yoursite/lists/yoursurvey/NewForm.aspx - It seems the Advanced setting "use open forms in dialog" doesn't work.
I have made this for a policy window. I made the whole thing inside of a content editor webpart which basically in invisible because the code has no appearence and I set the chrome type to none.
The other option is a feature which would replace the masterpage which is also not hard but requires a developement system for VS2010.
For the first method mentioned. You may have to strip the cookie stuff if you want it to load every time.
Create a new Content Editor Web Part with this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="disclaimer.js"></script>
Then create disclaimer.js:
_spBodyOnLoadFunctionNames.push("initialDisclaimerSetup");
var dialogTitle = "";
var dialogBody = "";
var dialogReturn = "";
var userID = _spUserId;
function initialDisclaimerSetup() {
if(getCookie("DisclaimerShown" + userID) == "Yes") {
return;
} else {
setCookie("DisclaimerShown" + userID, "No", 365);
}
getDisclaimerListItems();
}
function setCookie(cookieName, cookieValue, numExpireDays) {
var expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + numExpireDays);
document.cookie = cookieName + "=" + cookieValue + ";" +
"expires=" + ((numExpireDays == null) ? "" : expirationDate.toUTCString());
}
function getCookie(cookieName) {
if(document.cookie.length > 0) {
return document.cookie.split(";")[0].split("=")[1];
} else {
return "";
}
}
function getDisclaimerListItems() {
var listName = "Disclaimer";
var soapEnv = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<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:Body>"
+ "<GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">"
+ "<listName>" + listName + "</listName>"
+ "<query><Query><Where><IsNotNull><FieldRef Name=\"Title\" /></IsNotNull></Where></Query></query>"
+ "<ViewFields><ViewFields>"
+ "<FieldRef Name=\"Title\"/><FieldRef Name=\"Disclaimer\"/>"
+ "</ViewFields></ViewFields>"
+ "</GetListItems>"
+ "</soap:Body>"
+ "</soap:Envelope>";
$.ajax({
url: "_vti_bin/Lists.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
contentType: "text/xml; charset=\"utf-8\"",
complete: processResult
});
}
function processResult(xData, status) {
$(xData.responseXML).find("z\\:row").each(function() {
dialogTitle = $(this).attr("ows_Title");
dialogBody = $(this).attr("ows_Disclaimer");
launchModelessDialog();
if(dialogReturn == 0) {
return false;
} else if(dialogReturn == 1) {
} else if(dialogReturn == 2) {
return false;
}
});
if(dialogReturn == 0) {
getDisclaimerListItems();
} else if(dialogReturn == 1) {
setCookie("DisclaimerShown" + userID, "Yes", 365);
} else if(dialogReturn == 2) {
window.close();
}
}
function GetRootUrl() {
var urlParts = document.location.pathname.split("/");
urlParts[urlParts.length - 1] = "";
return "https://" + document.location.hostname + urlParts.join("/");
}
function launchModelessDialog(){
if (window.showModalDialog) {
window.showModalDialog("./disclaimer.htm", window, "dialogWidth:700px;dialogHeight:700px");
} else {
objPopup = window.open("./disclaimer.htm", "popup1", "left=100,top=100,width=800,height=800,location=no,status=yes,scrollbars=yes,resizable=yes, modal=yes");
objPopup.focus();
}
}
Then create disclaimer.htm:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<script type="text/javascript">
function initialRun() {
//var allArgs = dialogArguments;
var dialogTitle = dialogArguments.dialogTitle;
var dialogBody = dialogArguments.dialogBody;
dialogArguments.dialogReturn = "0";
document.getElementById('mainWrapper').innerHTML = "<h1>" + dialogTitle + "</h1>"
+ "<br/>" + dialogBody + "<br/><br/>";
}
function returnYes() {
dialogArguments.dialogReturn = 1;
window.close();
}
function returnNo() {
dialogArguments.dialogReturn = 0;
window.close();
}
function returnClose() {
dialogArguments.dialogReturn = 2;
window.close();
}
</script>
</head>
<body onload="initialRun()">
<div id="mainWrapper">
</div>
<div align="center">
<input name="acceptTOS" type="button" value="I Accept" onClick="returnYes();" />
<input name="acceptTOS" type="button" value="I Do NOT Accept" onClick="returnNo();" />
<input name="acceptTOS" type="button" value="Close" onClick="returnClose();" />
</div>
</body>
</html>
Then create a new Custom List called 'Disclaimer' and add a new column called 'Disclaimer' which allows for free text.

Resources