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)
});
}
);
});
}
Related
I created two test users from MESIBO API, to test messaging between them.
Created exact same script in two files, and add send function in one file, to send message to the second user.
I tried the second user's token, UID, and address but the message gets sent from the first user but 2nd user's script listener doesn't catch it. Both the user tokens, appid (app name) are valid, I tried even in HTTPS connection too, but still couldn't receive a message on another end.
Second User (two.html) : Sender
FIrst User (one.html) : Receiver
Script form first user: which supposed to get the message
<script type="text/javascript" src="https://api.mesibo.com/mesibo.js"></script>
<script>
var demo_user_token = 'XXXXXXXXXXXXXXXXXX';
var demo_appid = 'legal.web';
var api = new Mesibo();
api.setListener(new MesiboListener());
api.setAppName(demo_appid);
api.setCredentials(demo_user_token);
api.setAccessToken(demo_user_token);
//api.setDatabase("mesibo");
api.start();
console.log('First User');
function MesiboListener() {
}
MesiboListener.prototype.Mesibo_OnConnectionStatus = function(status, value) {
console.log("Mesibo_OnConnectionStatus: " + status);
}
MesiboListener.prototype.Mesibo_OnMessageStatus = function(m) {
console.log("Mesibo_OnMessageStatus: from "
+ m.peer + " status: " + m.status);
}
MesiboListener.prototype.Mesibo_OnMessage = function(m, data) {
console.log("Mesibo_OnMessage: from " + m.peer);
}
MesiboListener.prototype.Mesibo_OnCall = function(callid, from, video) {
console.log("Mesibo_onCall: " + (video?"Video":"Voice") + " call from: " + from);
}
</script>
Script from the second user, who send message to the first user using first user's token
<script type="text/javascript" src="https://api.mesibo.com/mesibo.js"></script>
<input type="button" value="Send" onclick="sendTextMessage()" >
<script>
var demo_user_token = 'XXXXXXXXXXXXXXXXXXX';
var demo_appid = 'legal.web';
var api = new Mesibo();
api.setListener(new MesiboListener());
api.setAppName(demo_appid);
api.setCredentials(demo_user_token);
api.setAccessToken(demo_user_token);
api.start();
console.log('Scond User User');
function MesiboListener() {
}
MesiboListener.prototype.Mesibo_OnConnectionStatus = function(status, value) {
console.log("Mesibo_OnConnectionStatus: " + status);
}
MesiboListener.prototype.Mesibo_OnMessageStatus = function(m) {
console.log("Mesibo_OnMessageStatus: from "
+ m.peer + " status: " + m.status);
}
MesiboListener.prototype.Mesibo_OnMessage = function(m, data) {
console.log("Mesibo_OnMessage: from " + m.peer);
}
function sendTextMessage() {
let to = "2757b980f05600c48d75f17f6cb0480ed3a91557655dc7d2ebb3f2dc5vaa1cbe86178"
var profile = api.getProfile(to, 0);
console.log(profile);
var id = parseInt(Math.random()*10000);
profile.sendMessage(id, "this is text message");
}
</script>
Why are you using a token in the "to" parameter? It should be the address "USER_2". Please do not share your tokens in a public forum.
function sendTextMessage() {
let to = "USER_2"
var profile = api.getProfile(to, 0);
console.log(profile);
var id = parseInt(Math.random()*10000);
profile.sendMessage(id, "this is text message");
}
Refer to the tutorial here https://mesibo.com/documentation/tutorials/get-started/javascript/
to check if page is published using server side code i should use this snippet:
PublishingPageCollection pages = PublishingWeb.GetPublishingWeb(web).GetPublishingPages();
foreach (PublishingPage page in pages)
{
if(!page.ListItem.File.Level == SPFileLevel.Published)
return;
// logic
}
How could i do the same but using Javascript in SharePoint?
According to SP.Publishing.PublishingWeb Methods the method GetPublishingPages is not supported in JSOM API.
But you could consider the following example to determine whether page is published or not using JSOM API
function getPublishingPages(success,error)
{
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle('Pages');
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
ctx.load(items,'Include(File)');
ctx.executeQueryAsync(function() {
success(items);
},
error);
}
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {
getPublishingPages(printPagesInfo,logError);
});
function printPagesInfo(pages)
{
pages.get_data().forEach(function(item){
var file = item.get_file();
var pageStatus = file.get_level() === SP.FileLevel.published ? 'published' : 'not published';
console.log(String.format('Page {0} is {1}', file.get_name(),pageStatus));
});
}
function logError(sender,args){
console.log('An error occured: ' + args.get_message());
}
Hi I'm trying to fetch the contacts from the phonebook using contact.find but i can't get it to work...
The addressbook is displayed and the when I choose a contact i get the ID but I don't get the rest of the information from this user that im trieng to alert in the onContactFound() function... what can be wrong??
<script type="text/javascript" charset="utf-8">
function pickContact()
{
var options = {};
navigator.contacts.chooseContact(onContactSelected, options);
}
function onContactSelected(id)
{
alert("Contact ID = " + id);
//TODO: How to look up the contact object by ID???
var options = new ContactFindOptions();
options.filter = "" + id;
var fields = ["id","displayName","addresses"];
navigator.contacts.find(fields, onContactFound, onContactFailure, options);
}
function onContactFound(contacts) {
alert(contacts.length + " contact(s) found"); //ex. 1 contact(s) found
alert("ID = " + contacts[0].id + ", Name = " + contacts[0].Name);
}
</script>
Property is name (or displayName), not Name, I suspect. Change contacts[0].Name.
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());
});
});
I have written a code following the documentation on phone gap website`
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
// find all contacts
var options = new ContactFindOptions();
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {
for (var i=0; i<contacts.length; i++)
{
console.log("Display Name = " + contacts[i].displayName);
var element = document.getElementById('cont');
element.innerHTML='<li>' + contacts[i].displayName + '</li>';
}
}
// onError: Failed to get the contacts
//
function onError(contactError) {
alert('onError!');
}
</script>`
It is working fine in andriod emulator but when i install the application samsung galaxy phone it return a "null". Kindly Help.
Strange... I also got null... (using Phonegap version 2.0)
I suggest you use something like contacts[i].name.formatted instead of contacts[i].displayName.
So, for example, by using contacts[i].name.formatted, your code should look like something like this:
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
// find all contacts
var options = new ContactFindOptions();
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {
var element = document.getElementById('cont');
for (var i=0; i<contacts.length; i++)
{
console.log("Display Name = " + contacts[i].name.formatted);
element.innerHTML='<li>' + contacts[i].name.formatted + '</li>';
}
}
// onError: Failed to get the contacts
//
function onError(contactError) {
alert('onError!');
}
Here are the different information that you can obtain with contacts[i].name:
contacts[i].name.givenName : provides the given name
contacts[i].name.formatted : provides a formatted name (first name + last name)
contacts[i].name.middleName : provides the middle name
contacts[i].name.familyName : provides the family name (first name + last name)
contacts[i].name.honorificPrefix : provides the honorific prefix
contacts[i].name.honorificSuffix : provides the honorific suffix
Hope this helps.
It is a complex problem with simple solution. just added only one line of code
options.filter="";
options.multiple=true;
var filter = ["*"];
That is complete code is
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
// find all contacts
var options = new ContactFindOptions();
options.filter="";
options.multiple=true;
var filter = ["*"];
navigator.contacts.find(filter, onSuccess, onError, options);
}
// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {
var ele = document.getElementById("cont");
var str = '<ul data-role="listview" >';
for (var i=0; i<contacts.length; i++) {
str=str + '<li>' + contacts[i].displayName + '</li>';
}
str = str + '</ul>';
// ele.innerHTML = str;
}
// onError: Failed to get the contacts
//
function onError(contactError) {
alert('onError!');
}
And it is working, by the way it also shows some null values as per the contact entries but it is working fine.
It may be iOS - http://docs.phonegap.com/en/2.1.0/cordova_contacts_contacts.md.html#Contacts. The docs say displayName isn't supported there. I'd follow Littm's advice, and also check the doc I linked to here as it talks about what properties don't work across different platforms.