Category: JQUERY

SharePoint List to JQuery Chart SharePoint Add In

JQuery Chart is easy to implement as a SharePoint Add In, in this sample I have retrieved SharePoint list data and formed it as JSON data and then JSON data object is passed into JQuey chart as input parameter. we can implement various type of chart using JQuery chart for as example bar, circle, line, doughnut, etc,… Here I’m going to explain detail about this SharePoint Add-In implementation.

You can download complete source code from the below URL

174https://code.msdn.microsoft.com/SharePoint-List-to-JQuery-90bfd45f

JQuery Chart SharePoint List

To create new project

Open visual studio 2015

On the file menu select New -> Project (Ctrl + Shift + N)

In the New Project window select or search “App for SharePoint”

In the “New App for SharePoint” wizard choose options based on your preferences

To add new resource file (.js or .css or Images) into project

Select a folder from solution explorer based on your file type (Images or Scripts or Content for CSS)

Right click and select “Open Folder in File Explorer” option

Now paste your files into the folder

Again in the solution explorer window at the top, click “Show All Files” icon

Now you can find the file without active icon, right click and select “Include in Project” Option

Solution compatibility

This sample is tested with SharePoint Online

This sample also compatible with SharePoint 2013 and SharePoint 2016

Code Flow

Fetching Host web URL and App web URL from query string

Host web content created using app web proxy

Retrieved list data from the host web

on the success event, list item collection converted as JSON data using JSON.parse

then the JSON data sent to chart js as parameter

//'use strict';

ExecuteOrDelayUntilScriptLoaded(initializePage, "sp.js");

function initializePage() {
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var hostweburl;
var appweburl;
var appContextSite;
var list;
var listItems;
var web;


// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
getUrl();
});

// This function get the URL informations
function getUrl() {
hostweburl = getQueryStringParameter("SPHostUrl");
appweburl = getQueryStringParameter("SPAppWebUrl");
hostweburl = decodeURIComponent(hostweburl);
appweburl = decodeURIComponent(appweburl).toString().replace("#", "");
var scriptbase = hostweburl + "/_layouts/15/";
$.getScript(scriptbase + "SP.RequestExecutor.js", execOperation);
}

// This function get list data from SharePoint
function execOperation() {
var factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
web = appContextSite.get_web();
context.load(web);
var camlQuery = new SP.CamlQuery();
list = web.get_lists().getByTitle("Post Reach");
listItems = list.getItems(camlQuery);
context.load(list);
context.load(listItems);
context.executeQueryAsync(onGetSPListSuccess, onGetSPListFail);
}


// This function is executed if the above call is successful
function onGetSPListSuccess() {
$("#DivSPGrid").empty();
var chartlabel = '';
var chartdata1 = '';
var chartdata2 = '';
var barChartData = '';
var listEnumerator = listItems.getEnumerator();
chartlabel = "{\"labels\":[";
chartdata1 = "],\"datasets\":[{" +
"\"fillColor\":\"rgba(220,220,220,0.5)\"," +
"\"strokeColor\":\"rgba(220,220,220,0.8)\"," +
"\"highlightFill\":\"rgba(220,220,220,0.75)\"," +
"\"highlightStroke\":\"rgba(220,220,220,1)\"," +
"\"data\":[";
chartdata2 = "]},{" +
"\"fillColor\":\"rgba(151,187,205,0.5)\"," +
"\"strokeColor\":\"rgba(151,187,205,0.8)\"," +
"\"highlightFill\":\"rgba(151,187,205,0.75)\"," +
"\"highlightStroke\":\"rgba(151,187,205,1)\"," +
"\"data\":[";
while (listEnumerator.moveNext()) {
var listItem = listEnumerator.get_current();
chartlabel += "\"" + listItem.get_item("Title") + "\",";
chartdata1 += listItem.get_item("Facebook") + ",";
chartdata2 += listItem.get_item("Twitter") + ",";
}
chartlabel = chartlabel.replace(/,\s*$/, "");
chartdata1 = chartdata1.replace(/,\s*$/, "");
chartdata2 = chartdata2.replace(/,\s*$/, "");
var str = chartlabel + chartdata1 + chartdata2 + ']}]}';
barChartData = JSON.parse(str);
var ctx = document.getElementById("chartCanvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, { responsive: true });
}

// This function is executed if the above call fails
function onGetSPListFail(sender, args) {
alert('Failed to get list data. Error:' + args.get_message());
}

//This function split the url and trim the App and Host web URLs
function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
}
<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>

<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>

<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
 <SharePoint:ScriptLink Name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
 <meta name="WebPartPageExpansion" content="full" />

 <!-- Add your CSS styles to the following file -->
 	<link rel="Stylesheet" type="text/css" href="../Content/App.css" />

 <!-- Add your JavaScript to the following file -->
 <script type="text/javascript" src="../Scripts/App.js"></script>
<script type="text/javascript" src="../Scripts/Chart.js"></script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
SPListItemCollection to JQuery Chart SharePoint Add In
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<div style="width: 50%">
<canvas id="chartCanvas" height="300" width="450"></canvas>
</div>
</asp:Content>

You can download complete source code from the below URL

174https://code.msdn.microsoft.com/SharePoint-List-to-JQuery-90bfd45f

Hope you find this article helpful, check out my other articles too.
Like my Facebook page to get future articles notification
Let me know your Queries and feedback in comments

Notification and Status messages SharePoint Add In

Introduction
There are multiple ways we can show notifications or status from SharePoint Add In, in this article we can find more detail about SharePoint Out of box notification, status and JQuery notification implementation logic

You can download complete source code from the below URL

zip_iconhttps://code.msdn.microsoft.com/Notification-and-Status-34bd280f

Solution compatibility
This sample is tested with SharePoint Online
This sample also compatible with SharePoint 2013 and SharePoint 2016

To create new project
Open visual studio 2015
On the file menu select New -> Project (Ctrl + Shift + N)
In the New Project window select or search “App for SharePoint”
In the “New App for SharePoint” wizard choose options based on your preferences

To add new resource file (.js or .css or Images) into project
Select a folder from solution explorer based on your file type (Images or Scripts or Content for CSS)
Right click and select “Open Folder in File Explorer” option
Now paste your files into the folder
Again in the solution explorer window at the top, click “Show All Files” icon
Now you can find the file without active icon, right click and select “Include in Project” Option

main notification

In the aspx page I have added six buttons and one text box to execute this sample and “notify.min.js” file added into project and refereed as script file reference.

<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>

<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>

<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
 <SharePoint:ScriptLink Name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
 <meta name="WebPartPageExpansion" content="full" />

 <!-- Add your CSS styles to the following file -->
 	<link rel="Stylesheet" type="text/css" href="../Content/App.css" />

 <!-- Add your JavaScript to the following file -->
 <script type="text/javascript" src="../Scripts/App.js"></script>
<script type="text/javascript" src="../Scripts/notify.min.js"></script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
Notification and Status messages SharePoint Add In
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<div id="divNotification">
<input type="button" name="btnAddNotification" id="btnAddNotification" value="Add Notification" />
</div>
<div id="divStatus">
<input type="button" name="btnAddStatus" id="btnAddStatus" value="Add Status" />
<input type="button" name="btnModifyStatus" id="btnModifyStatus" value="Modify Status" />
<input type="button" name="btnStatusColour" id="btnStatusColour" value="Change Status Colour" />
<input type="button" name="btnRemoveStatus" id="btnRemoveStatus" value="Remove Status" />
</div>
<div id="divJQueryStatus">
<input type="button" name="btnAddStatus" id="btnJQueryStatus" value="Add Status" />
</div>
<input type="text" id="txtName" value="" />

</asp:Content>

In the App.js file (which is located under scripts folder) cleanup all unnecessary code, and using css selector select buttons and write functions inside click event.

SharePoint Out of Box Status 

SP.UI.Status class provides methods for managing status messages. while we pass the color name as parameter to methods use lower case, Ex: red, green… if you pass it as “Red” then JavaScript won’t recognize it,because JavaScript is case sensitive.

SharePoint Out of Box Notification

SP.UI.Notify calss provides methods for managing notifications, we can pass notification message as HTML and by default, notifications appear for five seconds also we have option to adjusting this time

JQuery Notification

Notify.min.js used for JQuery notification, we can get extreme level of flexibility when we use JQuery notification also it is very simple to call with varies parameter. We can call any corner of the window or any side of the element

'use strict';

ExecuteOrDelayUntilScriptLoaded(initializePage, "sp.js");

function initializePage() {

//This function creates a new notification on your this Add-In
$('#btnAddNotification').click(function () {
//The message inside the notification.
var strHtml = "<img width='15px' src=\"../Images/loading.gif\" /> Loading <b>please wait...</b>";
//Specifies whether the notification stays on the page until removed.
var bSticky = false;
//Adds a notification to the page. By default, notifications appear for five seconds.
SP.UI.Notify.addNotification(strHtml, bSticky);
});
//The ID of the status to update.
var spstatus;
//this function Adds a status message to the Add-in page.
$('#btnAddStatus').click(function () {
//The title of the status message.
var strTitle = "SPTECHNET";
//The contents of the status message.
var strHtml = "New Status <b>massage</b>";
//Specifies whether the status message will appear at the beginning of the list.
var atBegining = true;
spstatus = SP.UI.Status.addStatus(strTitle, strHtml, atBegining);
//The color to set for the status message.
SP.UI.Status.setStatusPriColor(spstatus, "green");
});

$('#btnModifyStatus').click(function () {
//The new status message.
var strHtml = "Modified Status <b>massage</b>";
//Updates the specified status message.
SP.UI.Status.updateStatus(spstatus, strHtml);
//The color to set for the status message.
SP.UI.Status.setStatusPriColor(spstatus, "blue");
});

$('#btnStatusColour').click(function () {
var strColor = "red";
//The color to set for the status message.
SP.UI.Status.setStatusPriColor(spstatus, strColor);
});

$('#btnRemoveStatus').click(function () {
//Removes all status messages from the page.
SP.UI.Status.removeAllStatus(true);
});

$('#btnJQueryStatus').click(function () {
//Show JQuery status messages from the page.
$.notify("Access granted", "success");
$.notify("Warning: Self-destruct in 3.. 2..", "warn");
$('#txtName').notify("This field is required", "info");
$.notify("BOOM!", {
// whether to hide the notification on click
clickToHide: true,
// whether to auto-hide the notification
autoHide: false,
// if autoHide, hide after milliseconds
autoHideDelay: 5000,
// show the arrow pointing at the element
arrowShow: true,
// arrow size in pixels
arrowSize: 5,
// position defines the notification position though uses the defaults below
position: 'top right',
// default positions
elementPosition: 'top right',
globalPosition: 'top right',
// default style
style: 'bootstrap',
// default class (string or [string])
className: 'error',
// show animation
showAnimation: 'slideDown',
// show animation duration
showDuration: 400,
// hide animation
hideAnimation: 'slideUp',
// hide animation duration
hideDuration: 200,
// padding between element and notification
gap: 2
});
});
}

You can download complete source code from the below URL

zip_iconhttps://code.msdn.microsoft.com/Notification-and-Status-34bd280f

Hope you find this article helpful, check out my other articles too.
Like my Facebook page to get future articles notification
Let me know your Queries and feedback in comments

Export SharePoint List to Excel, Word, JSON, XML, SQL, CSV, TXT or PDF

Using JQuery we can export SharePoint list to Excel, Word, JSON, XML, SQL, CSV, TXT or PDF. Here I’m going to explain step by step explanation to implement this same in your environment. This will work for SharePoint 2013, 2016 and SharePoint online.

You can download complete source code from the below URL

zip_iconhttps://code.msdn.microsoft.com/Export-SharePoint-List-to-a802fd93

2016-02-17_23-46-38

Create “App for SharePoint” project in visual studio, in the new project creation wizard is select options based on your requirement. After project created rename your SharePoint App page, which is located under Pages folder, here I renamed as JQueryExport.aspx

Double click AppManifest.xml file and select SharePoint list view permission, because here we are just going read data from a SharePoint list, I’ve selected “Documents” list. List name and column name are hard coded  in the App.js file,


'use strict';

ExecuteOrDelayUntilScriptLoaded(initializePage, "sp.js");

function initializePage() {
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var hostweburl;
var appweburl;
var appContextSite;
var list;
var listItems;
var web;
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
getUrl();
});

// This function get the URL informations
function getUrl() {
hostweburl = getQueryStringParameter("SPHostUrl");
appweburl = getQueryStringParameter("SPAppWebUrl");
hostweburl = decodeURIComponent(hostweburl);
appweburl = decodeURIComponent(appweburl).toString().replace("#","");
var scriptbase = hostweburl + "/_layouts/15/";
$.getScript(scriptbase + "SP.RequestExecutor.js", execOperation);
}

// This function get list data from SharePoint
function execOperation() {
var factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
web = appContextSite.get_web();
context.load(web);
var camlQuery = new SP.CamlQuery();
list = web.get_lists().getByTitle("Documents");
listItems = list.getItems(camlQuery);
context.load(list);
context.load(listItems);
context.executeQueryAsync(onGetSPListSuccess, onGetSPListFail);
}
// This function is executed if the above call is successful
function onGetSPListSuccess() {
$("#DivSPGrid").empty();
var listInfo = '';
var listEnumerator = listItems.getEnumerator();
listInfo += "
<table id='SPTable' class='display'>
<thead>
<tr>" +
"
<th>Id</th>
" +
"
<th>Title</th>
" +
"
<th>Colour</th>
" +
"
<th>Modified By</th>
" +
"
<th>Modified date</th>
" +
"</tr>
</thead>
<tbody>";
while (listEnumerator.moveNext()) {
var listItem = listEnumerator.get_current();
listInfo += '
<tr>
<td>' + listItem.get_item('ID') + '</td>
'
+ '
<td>' + listItem.get_item('FileLeafRef') + '</td>
'
+ '
<td>' + listItem.get_item('Colour') + '</td>
'
+ '
<td>' + listItem.get_item('Editor').get_lookupValue() + '</td>
'
+ '
<td>' + listItem.get_item('Modified').format('dd MMM yyyy, hh:ss') + '</td>
'
+ '</tr>
';
}
listInfo += '</tbody>
</table>
';
$("#DivSPGrid").html(listInfo);
$('#SPTable').dataTable();
}

// This function is executed if the above call fails
function onGetSPListFail(sender, args) {
alert('Failed to get list data. Error:' + args.get_message());
}

//This function split the url and trim the App and Host web URLs
function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
}
<pre><!-- End --></pre>

Add CSS files into the ASPX


<!-- Add your CSS styles to the following file -->
	<link rel="Stylesheet" type="text/css" href="../Content/App.css" />
	<link href="../Content/ionicons.min.css" type="text/css" rel="stylesheet" />
	<link href="../Content/bootstrap.min.css" type="text/css" rel="stylesheet" />
	<link href="../Content/jquery.dataTables.css" type="text/css" rel="stylesheet" />

Add set of JS files as reference in your ASPX page


<!-- Add your JavaScript to the following file -->
 <!--our custom js file-->
 <script type="text/javascript" src="../Scripts/App.js"></script>

<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
 <script type="text/javascript" src="../Scripts/bootstrap.min.js"></script>
 <!--For export PDF file-->
 <script type="text/javascript" src="../Scripts/jspdf/libs/base64.js"></script>
 <script type="text/javascript" src="../Scripts/jspdf/libs/sprintf.js"></script>
 <script type="text/javascript" src="../Scripts/jspdf/jspdf.js"></script>
 <!--For export PNG file-->
 <script type="text/javascript" src="../Scripts/html2canvas.js"></script>
 <!--For export all other formats-->
 <script type="text/javascript" src="../Scripts/tableExport.js"></script>
 <script type="text/javascript" src="../Scripts/jquery.base64.js"></script>
 <!--For HTML Table format-->
 <script type="text/javascript" src="../Scripts/jquery.dataTables.js"></script>

I have used bootstrap drop down for listing export options,

<div class="dropdown">
<button class="btn btn-warning btn-sm dropdown-toggle" data-toggle="dropdown"><i class="fa fa-bars"></i>Export Table Data</button>
<ul class="dropdown-menu " role="menu">
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'json',escape:'false'});">
<img src="../Images/json.png" width='24px' />
JSON</a></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'json',escape:'false',ignoreColumn:'[0]'});">
<img src='../Images/json.png' width='24px' />
JSON (ignoreColumn)</a></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'json',escape:'true'});">
<img src='../Images/json.png' width='24px' />
JSON (with Escape)</a></li>
	<li class="divider"></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'xml',escape:'false'});">
<img src='../Images/xml.png' width='24px' />
XML</a></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'sql'});">
<img src='../Images/sql.png' width='24px' />
SQL</a></li>
	<li class="divider"></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'csv',escape:'false'});">
<img src='../Images/csv.png' width='24px' />
CSV</a></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'txt',escape:'false'});">
<img src='../Images/txt.png' width='24px' />
TXT</a></li>
	<li class="divider"></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'excel',escape:'false'});">
<img src='../Images/xls.png' width='24px' />
XLS</a></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'doc',escape:'false'});">
<img src='../Images/word.png' width='24px' />
Word</a></li>
	<li class="divider"></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'png',escape:'false'});">
<img src='../Images/png.png' width='24px' />
PNG</a></li>
	<li><a href="#" onclick="$('#SPTable').tableExport({type:'pdf',pdfFontSize:'7',escape:'false'});">
<img src='../Images/pdf.png' width='24px' />
PDF</a></li>
</ul>
</div>
<div id="DivSPGrid">
</div>
<script type="text/javascript">
 $(document).ready(function () {
 $('.dropdown-toggle').dropdown();
 });
 </script>

Let me know if you have any queries,

zip_iconhttps://code.msdn.microsoft.com/Export-SharePoint-List-to-a802fd93

SharePoint List to JQuery Table

We have lot of benefits using JQuery Table in SharePoint such as quick search, selecting of number of items in view, shorting and footer navigation. In this SharePoint Add-in, I’m retrieving SharePoint list data and building HTML table, then the HTML table mapped with JQuery Table script. Read further for detailed step by step instruction to develop this SharePoint Add-In.

2016-02-08_22-11-19

Create a new project in visual studio and select “App for SharePoint” project Template, in the new project wizard select SharePoint Hosted and select SharePoint environment type.

After the project is created, open Solution explorer, in that open App.js under Scripts folder and remove all default code which is generated by visual studio and paste the below Java script code into that page.


var context;
var hostweburl;
var appweburl;
var appContextSite;
var list;
var listItems;
var web;

$(document).ready(function () {
//SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getUrl);
getUrl();
});

function getUrl() {
hostweburl = getQueryStringParameter("SPHostUrl");
appweburl = getQueryStringParameter("SPAppWebUrl");
hostweburl = decodeURIComponent(hostweburl);
appweburl = decodeURIComponent(appweburl);
var scriptbase = hostweburl + "/_layouts/15/";
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js",
function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execOperation); }
);
}
);
event.preventDefault();
}

function execOperation() {
context = new SP.ClientContext(appweburl);
var factory =
new SP.ProxyWebRequestExecutorFactory(
appweburl
);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
web = appContextSite.get_web();
context.load(web);
var camlQuery = new SP.CamlQuery();
list = web.get_lists().getByTitle("Documents");
listItems = list.getItems(camlQuery);
context.load(list);
context.load(listItems);
context.executeQueryAsync(onGetSPListSuccess, onGetSPListFail);
}
function onGetSPListSuccess() {
$("#DivSPGrid").empty();
var listInfo = '';
var listEnumerator = listItems.getEnumerator();
listInfo += "
<table id='SPTable' class='display'>
<thead>
<tr>" +
"
<th>Id</th>
" +
"
<th>Title</th>
" +
"
<th>Modified By</th>
" +
"
<th>Modified date</th>
" +
"</tr>
</thead>
<tbody>";
while (listEnumerator.moveNext()) {
var listItem = listEnumerator.get_current();
listInfo += '
<tr>
<td>' + listItem.get_item('ID') + '</td>
'
+ '
<td>' + listItem.get_item('FileLeafRef') + '</td>
'
+ '
<td>' + listItem.get_item('Editor').get_lookupValue() + '</td>
'
+ '
<td>' + listItem.get_item('Modified').format('dd MMM yyyy, hh:ss') + '</td>
'
+ '</tr>
';
}
listInfo += '</tbody>
</table>
';
$("#DivSPGrid").html(listInfo);
$('#SPTable').dataTable();
}

// This function is executed if the above call fails
function onGetSPListFail(sender, args) {
alert('Failed to get SP List. Error:' + args.get_message());
}
function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}

Rename default.aspx page, which is located under pages folder based on your requirement here I have changed as JQueryTable.aspx.

Double click AppManifest.xml file and select List Read permission under Permissions tab.

Add JS file, CSS file and Images into respective folders, for reference see the below image. You can find the link to download the Full project at the end of this post.

2016-02-08_22-35-22

Add newly added JS and CSS files reference in the JQueryTable.aspx and add a new element of Div with id as DivSPGrid refer the below code for more detail.


<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>

<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>

<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
 <SharePoint:ScriptLink name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
 <meta name="WebPartPageExpansion" content="full" />

<!-- Add your CSS styles to the following file -->
 	<link rel="Stylesheet" type="text/css" href="../Content/App.css" />
 	<link href="../Content/jquery.dataTables.css" rel="stylesheet" />
 <!-- Add your JavaScript to the following file -->
 <script type="text/javascript" src="../Scripts/App.js"></script>
<script type="text/javascript" src="../Scripts/jquery.dataTables.js"></script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
SharePoint List to JQuery Table
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<div id="DivSPGrid">

</div>
</asp:Content>

Its time to review our SharePoint Add-in output, build and deploy the project and select “Document” in the SharePoint permission request page, you can change different list from the app.js file code as per your requirement.

Feel free to contact me thru comments if you face any issues.

Good Luck on building your code!!!

Output of our JQuery Table in SharePoint

2016-02-08_22-51-37

Actual SharePoint List for your reference

2016-02-08_22-53-22

zip_iconhttps://code.msdn.microsoft.com/SharePoint-List-to-JQuery-97dcee17

QR Code Generator Add-In for SharePoint

Using this you can generate QR Code for any text value and URL, this add-in can be add anywhere in you SharePoint Dashboard. Below you can see step by step instructions to develop this SharePoint Add-In. Also the complete project source code is available for download, find the download link at the bottom of this post.

2016-01-26_21-30-19

Create new Project in Visual studio using “App for SharePoint” template, here I’m using visual studio 2015 version. In the new project wizard select SharePoint-Hosted and rest you can select based on your requirements. Provider-Hosted application can also be selected.
I’ve added two JS files qr.js and initstrings.js, these JS files are developed by Microsoft. Here I modified those files. Modified files can be found in the project.

2016-01-26_18-44-22
Add new “Client Web Part (Host Web)” and select “Create a new app web page for the client web part content”, Edit newly created aspx page which is located in the Pages folder. Add below JS code and HTML. In the JS function I am passing Textbox value and Div name as parameter, JavaScript will generate QR code based on the content in Text box value.

 <script type="text/javascript">
 function generatefn() {
 if ($('#QR_URL').val() != '')
 onLoadQrCode($('#QR_URL').val(), 'DivImage');
 }
 </script>
 <input type="text" id="QR_URL" value="" style="width:250px" /><input onclick="generatefn()" type="button" id="btnGenerate" value="Generate" />
<div id="DivImage"></div>

Project source Download link

zip_icon https://code.msdn.microsoft.com/QR-Code-Generator-Add-In-a4cdd884

JQUERY BASICS – Part 2

load()
Using load method we can load other page’s full content or other page’s particular control inner HTML
Ex. Below code will load the MainDiv inner HTML. so inside the load method we need to pass page URL as a parameter if you want load full other source page or if you want to load particular element’s inner HTML then after the URL parameter give one space then enter the selector, here I’ve passed div id as selector (#MainDiv)

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>main page</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<b>HTML from another page:</b>

<div id="new-projects"></div>

 
<script>
 $("#new-projects").load("anotherpage.html #MainDiv");
</script>

</body>
</html>

This is the other source page

 

 
<!doctype html>
<html lang="en">
<head>
<title>another page</title>
</head>
<body>
full HTML contents From another page
<div id="MainDiv">
<h3 style="color:green">div inner html from another page</h3>
</div>
</body>
</html>

OutPut

2016-01-16_16-33-35

each()

each() will take collection from selector and loop the items, this is same as Foreach in c#.
Ex. Below code will loop the all div elements and elements inner HTML append into one p tag.

 
<!DOCTYPE html>
<html>
<head>
<title>For Each</title>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
 <script>
 $(document).ready(function () { $('div').each(function () { $('.ptag').append($(this).html()); }); });

 </script>
</head>
<body>
<div>Div 1</div>
<div>Div 2</div>
<div>Div 3</div>
<div>Div 4</div>
<p class="ptag"></p>


</body>
</html>

Output

2016-01-16_16-34-27

slideToggle()

The jQuery library provides several techniques for adding animation to a web page, slideToggle will hide and show the targeted element,

Ex, below code will hide and show the all div elements

</pre>
<!DOCTYPE html>
<html>
<head>
<title>Show Hide</title>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<div>Div 1</div>


<div>Div 2</div>


<div>Div 3</div>


<div>Div 4</div>

 <input type="button" id="button" value="click here" />
 <script>
 $('#button').click(function () { $('div').slideToggle(1500); });
 </script>
</body>
</html>

JQUERY BASICS – Part 1

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

jquery-logo

In jQuery all the codes starts with “jquery” it’s kind of a door, but when we write some long functionality we can see lot of jquery terms in the code. We don’t really want to repeat it everywhere, instead of “jquery” we can use “$” symbol.


jquery == $

Ex, below are two methods that return the same o/p. In this example we write hello world in the browser console (F12 shortcut key to open browser console window) after the page load.


jQuery(function () { console.log('hello world'); });

OR

$(function () { console.log('hello world'); });

Selectors

We can use CSS3 Selectors for selecting particular tag or set of tags from the page.

Ex,


<html> <head>
<style> p { background-color: #ffc022; } </style>

 </head> <body>
<div id="container">
<h1 class="Info">Introduction</h1>
<a href="/newpage">move to the new page</a></div>
</body> </html>

In the above HTML code we call div using id, in this method id should be unique,

$(‘#container’)

Values for class be repeated and have multiple space-separated values

$(‘.Info’)

Adding and Removing CSS class

After selecting using selector we can add or remove CSS class using below methods

$( "p" ).addClass( "newClass onemoreClass" )

$( "p" ).removeClass( "newClass onemoreClass " )

Events

In the jQuery we can call events in varies ways, in below method we add a function within click event. We have lot of events available in jQuery.

$( "#butSave" ).click(function() {

alert( "Handler for .click() called." );

});

Another method, here we are attaching the event into a button.

$( "#btnSave" ).on( "click", function() {
alert( "Handler for click called using event attach method " );

});

Below code will remove the event attachment from button.

$( "#btnSave" ).off( "click", function() {

alert( "Handler for click is removed" );

});

Below code will fire only once, there is some other event attaching methods also available in jQuery

$( "#btnSave" ).one( "click", function() {

alert( "Handler for click called using event attach method " );

});

Selecting right version of jQuery

There are two major release available in jQuery, one is 1.x and another is 2.x. Select 1.x version if you want to support your application in IE 8 and the below version browsers,else select 2.x.