Sharepoint 2013 Online - Display currentUser information in page - javascript

I need to get the currentUser information, like email address and or name when a Home.aspx page is loaded in a specific area on the page like maybe the footer area. I have search and every JavaScript that I have found do not work.
I need the text to display either in a Script Editor or Content Editor or an XML file.
What is wrong with the following JavaScript that I found. I have it in the WebApp Script Editor:
<script type=”text/javascript”>
ExecuteOrDelayUntilScriptLoaded(init,”sp.js”);
var currentUser;
function init(){
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}
function onQuerySucceeded() {
document.getElementById(“logUser”).innerHTML = currentUser.get_loginName();
}
function onQueryFailed(sender, args) {
alert(‘Request failed. \nError: ‘ + args.get_message() + ‘\nStackTrace: ‘ + args.get_stackTrace());
}
< /script>
< div>Current Logged User:<label id=”logUser”></label></div>
Can anyone help me?

Most probably init method is not executed since SP.SOD.executeOrDelayUntilScriptLoaded method expects SharePoint Client Library sp.js to be loaded first.
Use SP.SOD.executeFunc method instead since it supports on demand scripts.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext',function(){
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var currentUser = web.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(
function(){
console.log(currentUser.get_loginName());
},
function(sender, args){
console.log('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
});
});

Related

Facebook email is returned as undefined from phonegap facebookConnect plugin

I am using the phonegap facebook Connect plugin to enable facebook login in my app.
However the facebook email is being returned as undefined.
Do I need to add something into my code?
I have looked up this issue on the internet and it seems my code should work. Everything else is returned except for the email address.
I would appreciate if you can help
Here is my javascript code:
facebookConnectPlugin.api('/me?fields=id, email, link, name, picture', ["public_profile"],function(data){
var fb_user_id = data.id;
var fb_email = data.email;
var fb_name = data.name;
var fb_picture_url = data.picture.data.url;
var fb_user_link = data.link;
alert("fb_email" + fb_email);
}); //end api call
Edit:
I tried a test user account with this code and the email address DID get returned. However for the real account I was testing with this doesn't work.
With more testing I tried adding in the email permission as follows however this did not work as the data that I got back stated "FACEBOOK_NON_JSON_RESULT"
facebookConnectPlugin.api('/me?fields=id, email, link, name, picture', ["public_profile", "email"],function(data){
var fb_user_id = data.id;
var fb_email = data.email;
var fb_name = data.name;
var fb_picture_url = data.picture.data.url;
var fb_user_link = data.link;
alert("fb_email" + fb_email);
}); //end api call
I find a workaround for this problem which was to do two separate api requests as follows:
facebookConnectPlugin.api('/me?fields=email', ["email"], function(apiResponse) {
//alert("api" + JSON.stringify(apiResponse));
fb_email = apiResponse.email;
alert("fb_email" +fb_email); //email being retrieved successfully
facebookConnectPlugin.api('/me?fields=id, name, link, picture', ["public_profile"],function(data) {
alert("data" + JSON.stringify(data));
var fb_user_id = data.id;
var fb_name = data.name;
var fb_picture_url = data.picture.data.url;
var fb_user_link = data.link;
alert("fb_user_id" + fb_user_id);
alert("fb_name" + fb_name);
alert("fb_picture_url" + fb_picture_url);
alert("fb_user_link" + fb_user_link);
//do stuff with facebook user data here
}
,function(error){
//api call failed
alert("api call Failed: " + JSON.stringify(error));
}); //end api
}
,function(error){
alert("email api call Failed: " + JSON.stringify(error));
}); //end api
This works perfect!

Fetching data from spreadsheet in script: "Data table is not defined"

I’m trying to make a script using the Google Visualization App Geomap. In the example code on the Google Developers page, they are using a hard coded table. What I want to do, is to make code use data from a Google Spreadsheet connected to a Google Form. More specifically, I want to use the data of the spreadsheet tab «countries» from the following spreadsheet: https://docs.google.com/spreadsheets/d/1l77TXctG6mgva1ggs3iR3eBNx949hzn9SiVjki1v59I/edit?usp=sharing.
Somehow this does not work, and I get the error messages listed below.
How can I collect the data from the spreadsheet in the right format? I have attempted to use this procedure to collect the data from the spreadsheet: https://google-developers.appspot.com/chart/interactive/docs/spreadsheets.
Error message on web page:
"Data table is not defined"
Error message in Safari Console:
TypeError: undefined is not an object (evaluating 'new google.visualization.Query’)
drawChart help:113
(anonymous function) help:117
My code
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["geomap"]});
google.setOnLoadCallback(drawMap);
function drawMap() {
var opts = {sendMethod: 'auto'};
// ***My code***
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1l77TXctG6mgva1ggs3iR3eBNx949hzn9SiVjki1v59I/edit#gid=957991050', 'sheet=countries', 'headers=1');
var data = query.send(handleQueryResponse);
var options = {};
options['dataMode'] = 'regions';
var container = document.getElementById('regions_div');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
};
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
return response.getDataTable();
}
</script>
Hope there is someone out there who can help me with this (hopefully) not so hard task. Thank you very much in advance! :-)
You can get data inside of a callback function handleQueryResponse
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
} else {
var container = document.getElementById('regions_div');
var geomap = new google.visualization.GeoMap(container);
var data = response.getDataTable();
geomap.draw(data, options);
}
}
Google provides example here.
Also check format which you get in response and use method google.visualization.arrayToDataTable to format data as in example if needed cause it format should be correct.

SharePoint Workflow Subscription Service failed

I have one requirement to start the SP workflow through JavaScript. For this, i have wrote some lines of code to start the workflow.But I am getting a Subscription failed error due to undefined object. This is occuring at ExcecuteasyncQuery method. So i didn't get which object returns the undefined value. My code is shown below.
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.core.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.workflowservices.js"> </script>
<script type="text/javascript">
var subID = "3debdbad-db52-4586-87e1-40e4db581da5";
function GetCurrentItemID()
{
var ctx = SP.ClientContext.get_current();
var selectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
for (item in selectedItems)
{
var itemId = selectedItems[item].id;
startWorkflow(itemId, subID);
}
}
function startWorkflow(itemID, subID) {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var wfServiceManager = SP.WorkflowServices.WorkflowServicesManager.newObject(context, web);
var subscription = wfServiceManager.getWorkflowSubscriptionService().getSubscription(subID);
context.load(subscription);
context.executeQueryAsync(
function(sender, args){
alert("Subscription load success. Attempting to start workflow.");
var inputParameters = {};
wfServiceManager.getWorkflowInstanceService().startWorkflowOnListItem
(subscription, itemID, inputParameters);
context.executeQueryAsync(
function(sender, args){ alert("Successfully starting workflow."); },
function(sender, args){
alert("Failed to start workflow.");
alert("Error: " + args.get_message() + "\n" + args.get_stackTrace());
}
);
},
function(sender,args){
alert("Failed to load subscription.");
alert("Error: " + args.get_message() + "\n" + args.get_stackTrace());
}
);
}
</script>
I am calling the GetCurrentItemID() function at the button click. But at that time, i am getting the following error.
Failed to load subscription
Invalid Request
Undefined
Could any one please help me to sort out this issue. Thanks in advance.
According to the script and the error message,
I suggest you check whether the “subscription” and “itemId” objects hold the proper values.
What’s more, you can take a look at the two links below about how to start workflow using JavaScript Client Object Model:
http://usamawahabkhan.blogspot.com/2013/07/start-workflow-sharepoint-2010.html
https://sharepoint.stackexchange.com/questions/87015/solved-start-a-workflow-of-the-host-web-via-sharepoint-app-and-jsom
Feel free to reply with the test result or if there are any progress.
Building on the solutions provided by others, here's the code I was able to use. NOTE: You need to have your workflow set to "Allow this workflow to be started manually."
/**
* Starts a SharePoint 2013 Workflow on a particular list item.
* Params:
* workflowName: The name of the Workflow
* listGUID: the GUID of the list
* itemId: the ID of the list item
*/
function startListWorkflow(workflowName, listGUID, itemId){
SP.SOD.executeFunc("sp.js", "SP.ClientContext" , function(){
SP.SOD.registerSod('sp.workflowservices.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js'));
SP.SOD.executeFunc('sp.workflowservices.js', "SP.WorkflowServices.WorkflowServicesManager",
function(){
var ctx = new SP.ClientContext.get_current(),
wfsManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web()),
wfSubs = wfsManager.getWorkflowSubscriptionService().enumerateSubscriptionsByList(listGUID);
ctx.load(wfSubs);
ctx.executeQueryAsync(function () {
wfsEnum = wfSubs.getEnumerator();
while (wfsEnum.moveNext()) {
var wfSub = wfsEnum.get_current();
if (wfSub.get_name() === workflowName) {
var initiationParams = {};
wfsManager.getWorkflowInstanceService().startWorkflowOnListItem(wfSub, itemId, initiationParams);
ctx.executeQueryAsync(
function (sender, args) {
console.log("Successfully started workflow.");
},
function (sender, args) {
console.log("Failed to start the workflow.");
console.log("Error: " + args.get_message() + "\n" + args.get_stackTrace());
}
);
}
}
},function(e){
console.error(e)
});
}
);
});
}

Script does not work from shell but works from remote debugger

I am trying to automate a bugzillametrics query. From a browser, If I do
http://10.x.x.x:8080/BugzillaMetrics1_3/#calculate_query,1.1.1, the query works fine and i can get the relevant graph from bugzillametrics. In order to automate this progress, I am using phantomjs. My phantomjs script is as follows:
var webPage = require('webpage');
var page = webPage.create();
var postBody1 = '';
page.open('http://10.x.x.x:8080/BugzillaMetrics1_3/#calculate_query,1.1.1 ',function(status) {
console.log('Status: ' + status);
var content = page.content;
console.log('Content: ' + content);
page.onError = function (msg, trace) {
console.log(msg);
trace.forEach(function(item) {
console.log(' ', item.file, ':', item.line);
});
};
phantom.exit();
});
If I run the script using "./phantomjs post1.js", the bugzillametrics does not create the necessary output. In fact, all i get is status = success. However, If I open the remote debugger and execute the same script using "__run()", I get correct results. What should I do different from the shell ?

SharePoint ECMAScript for Mobile devices

I'm trying to execute some javascript code (SharePoint ECMA script model) to access SP data on mobile devices. However, the following code fails.
$(document).ready(function(){
var clientContext = new SP.ClientContext.get_current();
this.oWebsite = clientContext.get_web();
clientContext.load(this.oWebsite);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed));
});
function onQuerySucceeded(sender, args) {
alert('Title: ' + this.oWebsite.get_title() + ' Decription: ' + this.oWebsite.get_description()); }
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace()); }
Even, this code also fails on desktop browsers. Any idea?
"Document ready" won't work. Instead call the SharePoint 2010 method ExecuteOrDelayUntilScriptLoaded. This must be added as the very first line of code after the script tag. It will call your method when the SP Object is successfully loaded. This resolves your issue on desktop browsers, I assume it will work for your mobile solution too.
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(function () {
YourFunction()
},"sp.js");

Categories