SharePoint ECMAScript for Mobile devices - javascript

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");

Related

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 2013 Online - Display currentUser information in page

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());
});
});

Autobahn.js - subscribe doesn't work with websockets

I'm using Ratchet WebSockets and Autobahn.js for two-way client-server communication. I've installed everything, opened the ports, it's been weeks (yes, literally weeks) and it still doesn't work. I think I've narrowed it down to Autobahn's subscribe method not working correctly.
What I'm using is a slight modification of the example code found here:
http://socketo.me/docs/push
Here is my client code:
<script>
window.define = function(factory) {
try{ delete window.define; } catch(e){ window.define = void 0; } // IE
window.when = factory();
};
window.define.amd = {};
</script>
<script src="/apps/scripts/when.js"></script>
<script src="http://autobahn.s3.amazonaws.com/js/autobahn.min.js"></script>
<script>
var conn = new ab.Session(
'ws://light-speed-games.com:8080' // The host (our Ratchet WebSocket server) to connect to
, function() { // Once the connection has been established
console.log('Connection established.');
conn.subscribe('kittensCategory', function(topic, data) {
// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
console.log('New article published to category "' + topic + '" : ' + data.title);
});
}
, function() { // When the connection is closed
console.warn('WebSocket connection closed');
}
, { // Additional parameters, we're ignoring the WAMP sub-protocol for older browsers
'skipSubprotocolCheck': true
}
);
</script>
I believe the problem lies here:
function() { // Once the connection has been established
console.log('Connection established.');
conn.subscribe('kittensCategory', function(topic, data) {
// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
console.log('New article published to category "' + topic + '" : ' + data.title);
});
}
The line console.log('Connection established.'); does its job - it logs its message in the console. However, the conn.subscribe method does nothing. It doesn't matter if I change kittensCategory to any other string, it still does nothing. But kittensCategory is the only thing that makes sense here (see Ratchet's example code through the link above).
Any ideas?
EDIT:
This is the output of ab.debug:
WAMP Connect autobahn.min.js:69
ws://light-speed-games.com:8080 autobahn.min.js:69
wamp autobahn.min.js:69
WS Receive autobahn.min.js:64
ws://light-speed-games.com:8080 [null] autobahn.min.js:64
1 autobahn.min.js:64
[0,"52cbe9d97fda2",1,"Ratchet\/0.3"] autobahn.min.js:64
WAMP Welcome autobahn.min.js:67
ws://light-speed-games.com:8080 [52cbe9d97fda2] autobahn.min.js:67
1 autobahn.min.js:67
Ratchet/0.3 autobahn.min.js:67
Connection established. client.php:15
WAMP Subscribe autobahn.min.js:74
ws://light-speed-games.com:8080 [52cbe9d97fda2] autobahn.min.js:74
kittensCategory autobahn.min.js:74
function (topic, data) {
// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
console.log('New article published to category "' + topic + '" : ' + data.title);
} autobahn.min.js:74
WS Send autobahn.min.js:72
ws://light-speed-games.com:8080 [52cbe9d97fda2] autobahn.min.js:72
1 autobahn.min.js:72
[5,"kittensCategory"]

Phonegap/Cordova InAppBrowser not launching

I am not sure why but when I do the following
<img id="buttons" src="https://qikout.com/apppics/MerchantPromo.png" style="margin:1% auto; width:99% !important;" onclick="openextlink('https://qikout.com');"/>
function openextlink(url)
{
var ref = window.open(url, '_blank', 'location=no');
//window.plugins.childBrowser.showWebPage(url, { showLocationBar: true });
}
it works fine. But when I want to run the openextlink from within another function it does not open the window, instead it loads the page but just does not show it to the user.
for e.g.
function scan(){
window.plugins.barcodeScanner.scan( function(result) {
if(result.format != "QR_CODE")
{
alert("That is not a valid google Tag");
}
else
{
n = result.text.split(".com/");
loadpet();
//alert("We got a barcode\n" +
// "Result: " + result.text + "\n" +
// "Format: " + result.format + "\n" +
// "Cancelled: " + result.cancelled);
}
}, function(error) {
alert("Scanning failed: " + error);
}
);
}
function loadpet(){
$("#buttons").trigger("click");
var link = "http://www.google.com/" + n[1];
openextlink(link);
}
it works via
<div onclick="scan();" class="menu-right"></div>
Basically it scans fine, it gets the result it moves the result to the loadpet function and even sends it to the openextlink function however does not popup the viewer.
Your window.open code looks right (based on how InAppBrowser works as of Cordova 3.0).
Can you confirm all of the following?
The InAppBrowser plugin has an entry in your /#myapp#/platforms/#platform#/www/cordova_plugins.js file?
The InAppBrowser plugin folder is in /#myapp#/platforms/#platform#/plugins/
The related SRC files for InAppBrowser are in the platform folder as well (for example IOS plugin src files are: /#myapp#/platforms/#platform#/#appname#/Plugins/)
Also if all the above are confirmed but still no luck you might try appending a console.log('inappbrowser.js file has loaded!') line to the end of your inappbrowser.js file to confirm it is indeed loading (assuming you have setup the debug console and can view the output).

Categories