I've been asked to look at a website. I have little html background but would like to access some SharePoint information with javascript. I opened up my console and tried:
var value = SP.Web.get_currentUser();, but it was an Uncaught TypeError.
_spPageContextInfo.userId; on the otherhand, works.
Any thoughts on how to get the first one working?
Thank you
You cannot access the Web.get_currentUser() without loading first.
You can get currentUser() like:
var clientContext = new SP.ClientContext.get_current();
var oWeb = clientContext.get_web();
currentUser = oWeb.get_currentUser();
clientContext.load(currentUser); // prepare your query
clientContext.executeQueryAsync( // submit your query to the server
function(){ // on success
// var loginName = currentUser.get_loginName();
// var userId = currentUser.get_id();
// var userTitle = currentUser.get_title();
// var userEmail = currentUser.get_email();
}, function(){ // on error
alert('Error: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
});
Read more on here: https://sharepoint.stackexchange.com/a/128137
Related
This is my first time working with XML and I am not that techy but trying to get to understand programming to make my work easier. I am using Google App script and finding it a challenge in passing XML data that I get via API.
I need to get this data so that I can set the specific values to Google sheets using google app script.
I am not sure how to iterate/loop through elements to get everyone's data and then set it to google sheet.
And here is the code I have worked on so far. When I log to say the first name, I only get one name instead of about 50 names in the system. Any help here will highly be appreciated.
ak ='key'
start = '2019-01-01'
end = '2019-12-31'
function getData() {
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + ak
}
};
var url = 'https://data.purelyhr.com/daily?ak='+ ak + '&sDate=' + start + '&eDate=' + end + '&TimeOffTypeName';
var response = UrlFetchApp.fetch(url).getContentText();
var document = XmlService.parse(response);
var root = document.getRootElement();
//set variables to data from PurelyHR
var TimeOffDate = root.getChild('Request').getChild('TimeOffDate').getText();
var TimeOffDayOfWeek = root.getChild('Request').getChild('TimeOffDayOfWeek').getText();
var TimeStart = root.getChild('Request').getChild('TimeStart').getText();
var TimeEnd = root.getChild('Request').getChild('TimeEnd').getText();
var TimeOffHours = root.getChild('Request').getChild('TimeOffHours').getText();
var TimeOffTypeName = root.getChild('Request').getChild('TimeOffTypeName').getText();
var LoginID= root.getChild('Request').getChild('LoginID').getText();
var Firstname = root.getChild('Request').getChild('Firstname').getText();
var Lastname = root.getChild('Request').getChild('Lastname').getText();
var UserCategory = root.getChild('Request').getChild('UserCategory').getText();
var SubmittedDate = root.getChild('Request').getChild('SubmittedDate').getText();
var Deducted = root.getChild('Request').getChild('Deducted').getText();
var Comment = root.getChild('Request').getChild('Comment').getText();
//populate the sheet with variable data
Logger.log(response)
}
Sample response
<?xml version='1.0' encoding='ISO-8859-1'?>
<DataService>
<Request ID="1253" Status="Approved">
<TimeOffDate>2020-02-07</TimeOffDate>
<TimeOffDayOfWeek>Friday</TimeOffDayOfWeek>
<TimeStart></TimeStart>
<TimeEnd></TimeEnd>
<TimeOffHours>8.000</TimeOffHours>
<TimeOffTypeName>Annual Vacation</TimeOffTypeName>
<LoginID>testuser</LoginID>
<Firstname>test</Firstname>
<Lastname>user</Lastname>
<UserCategory></UserCategory>
<SubmittedDate>2019-10-03</SubmittedDate>
<Deducted>Yes</Deducted>
<Comment>
<![CDATA[* time-off request created by administrator]]>
</Comment>
</Request>
<Request ID="126292" Status="Approved">
<TimeOffDate>2020-02-07</TimeOffDate>
<TimeOffDayOfWeek>Friday</TimeOffDayOfWeek>
<TimeStart></TimeStart>
<TimeEnd></TimeEnd>
<TimeOffHours>8.000</TimeOffHours>
<TimeOffTypeName>Annual Vacation</TimeOffTypeName>
<LoginID>usertwo</LoginID>
<Firstname>user</Firstname>
<Lastname>two</Lastname>
<UserCategory></UserCategory>
<SubmittedDate>2019-10-15</SubmittedDate>
<Deducted>Yes</Deducted>
<Comment>
<![CDATA[Neil (as my mentor)]]>
</Comment>
</Request>
If I understand correctly, the problem is that you have multiple <Request> elements, but your code is only looking at one of them. This is because you're using getChild(), which will only provide the first element with the given name.
I can't fully test that this works because you haven't provided the XML text, but you should instead use the getChildren() method to get all of the Request elements. Then you can loop through that.
function getData() {
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + ak
}
};
var url = 'https://data.purelyhr.com/daily?ak=' + ak + '&sDate=' + start + '&eDate=' + end + '&TimeOffTypeName';
var response = UrlFetchApp.fetch(url).getContentText();
var document = XmlService.parse(response);
var root = document.getRootElement();
//set variables to data from PurelyHR
var requestElements = root.getChildren('Request'); // Get all <Request> elements
var requestObjects = []; // Request objects for logging / eventual printing
for (var i = 0; i < requestElements.length; i++) {
var request = requestElements[i]; // A single <Request> element
// Add to requestObjects array
requestObjects.push({
TimeOffDate: request.getChild('TimeOffDate').getText(),
TimeOffDayOfWeek: request.getChild('TimeOffDayOfWeek').getText(),
TimeStart: request.getChild('TimeStart').getText(),
TimeEnd: request.getChild('TimeEnd').getText(),
TimeOffHours: request.getChild('TimeOffHours').getText(),
TimeOffTypeName: request.getChild('TimeOffTypeName').getText(),
LoginID: request.getChild('LoginID').getText(),
Firstname: request.getChild('Firstname').getText(),
Lastname: request.getChild('Lastname').getText(),
UserCategory: request.getChild('UserCategory').getText(),
SubmittedDate: request.getChild('SubmittedDate').getText(),
Deducted: request.getChild('Deducted').getText(),
Comment: request.getChild('Comment').getText()
});
}
Logger.log(JSON.stringify(requestObjects));
}
Since I don't know how you're printing, I created an array of request objects and logged that in the sample above. I hope this made sense, but please let me know if you have any questions or if I'm completely off with my response.
I've got a problem with JSON in JavaScipt. I've got 2 different JSON URL. One of them contains data about users and the second one about posts. And in posts JSON I've got a field userId.
I want to find a way to connect them somehow. I need to get users and their posts and then count how many posts every user wrote.
var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
var posts = JSON.parse(postRequest.responseText);
var userRequest = new XMLHttpRequest();
userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
userRequest.onload = function (){
var users = JSON.parse(userRequest.responseText);
for(k in users){
document.write("</br></br>"+ users[k].name +", " + users[k].username + ", " + users[k].email + "</br>" + "-------------------------------------------------------------------------------------" + "</br>");
for(k1 in posts){
if(posts[k1].userId===users[k].id){
document.write(posts[k1].body + "</br>");
}
}
}
};
userRequest.send();
};
postRequest.send();
but I think it doesn't look good. I want to get data from JSON to variable to use them later, in function for example.
Anyone help? I've never connected data from 2 JSON files and want to do it in a good way and getting good practice.
Use this instead
for(k in users){
for(k1 in posts){
if(posts[k1].userId===users[k].id){
if(!users[k].hasOwnProperty('posts')) {
users[k].posts = [];
}
users[k].posts.push(posts[k1].body);
}
}
}
if you could you jquery
$.when($.ajax({
url: "https://jsonplaceholder.typicode.com/users"
})).then(function(data, textStatus, jqXHR) {
$.each(data, function(index, value) {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts?userId=" + value.id
}).then(function(data, textStatus, jqXHR) {
console.log("UserID:" + data[0].userId + " Nos Posts:" + data.length);
});
});
});
You can try above code and let me know if it solve your purpose
Steps you can use :
1. You can add a body property in to the objects in users array as per the id and userid match.
2. Later you can iterate the users array whenever you want to use.
DEMO
var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
var posts = JSON.parse(postRequest.responseText);
var userRequest = new XMLHttpRequest();
userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
userRequest.onload = function (){
var users = JSON.parse(userRequest.responseText);
for(k in users) {
for(k1 in posts) {
if(posts[k1].userId===users[k].id){
users[k].body = posts[k1].body;
}
}
}
console.log("users", users);
};
userRequest.send();
};
postRequest.send();
Hello I have the following code in a Content Editor Web Part, which retrieves the current user's name and displays it in a message box :
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function getUser() {
var userid = _spPageContextInfo.userId;
//alert(userid);
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept": "application/json;odata=verbose" };
$.ajax({
url: requestUri,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
success: onSuccess,
error: onError
});
function onSuccess(data, request) {
var loginName = data.d.Title;
alert(loginName);
}
function onError(error) {
alert("Error on retrieving current user.");
}
}
$(document).ready(function() {
getUser();
});
</script>
I was also able to display the email with alert(data.d.Email);.
However, when I try calling data.d.Groups (as per the documentation - which shows that a Groups property exists), I see a message box with [object Object].
How can I retrieve the individual items from this (what I am assuming is a) collection?
I have tried :
var group = data.d.Groups[0];
alert(group);
But this just comes up with undefined.
Am I wrong in thinking that this object will contain my Department?
Either way, is there a way of iterating through these objects, or have I done it correctly but on an empty array?
Thank you
Attempt at Logging the groups
function onSuccess(data, request) {
var loginName = data.d.Title;
console.log(loginName);
var groups = data.d.Groups;
console.log(groups);
}
I can't see either of the above logs in the F12 console window... (Internet Explorer)
Attempt 2 - Logging Successful
Using the code below, I was able to achieve the same results as before, but this time the console.log() calls actually worked (still have no idea why the previous ones didn't):
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() {
var groups = currentUser.get_groups();
alert(groups);
console.log(groups);
var name = currentUser.get_loginName();
alert(name);
console.log(name);
var id = currentUser.get_id();
alert(name);
var title = currentUser.get_title();
alert(title);
var email = currentUser.get_email();
alert(email);
}
function onQueryFailed(sender, args) {
alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
After calling console.log(groups);, the following appeared in the F12 console :
"data.d.Groups" is the Object, When you pass this into .html(data.d.Groups) you will get it as [object Object] only because object will convert as the string Just loop the object and you will get the key and value
for (key in data.d.Groups){
alert("key: " + key + "value :" + data.d.Groups[key]);
}
I was able to find a rather ugly solution to this, but it does work.
First, we need to call some .js files in preperation:
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
<script src="/_layouts/15/SP.Runtime.js"></script>
<script src="/_layouts/15/SP.js"></script>
<script src="/_layouts/15/SP.UserProfiles.js"></script>
Then, inside a <script language="javascript" type="text/javascript"> tag, we declare some global variables and 2 main functions...
var currentUser;
var currentUserName;
var property = "Department";
1. GetCurrentUserProperty(property):
This function actually only gets the current user for us and, if successful will call loadUserData (which actually gets the property we defined earlier for the given user:
// This function first gets the current user's firstname.lastname username (e.g. Joe.Bloggs).
// If this is successful, it calls the loadUserData function, which will retrieve the user's
// property which was defined in the global "property" variable.
function GetCurrentUserProperty(){
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
this.clientContext.executeQueryAsync(onQueryUserSuccess, onQueryUserFail);
}
function onQueryUserSuccess() {
// If the query is successful, extract the first.last username and then call loadUserData
window.currentUserName= currentUser.get_loginName().split("\\")[1];
loadUserData(window.currentUserName);
}
function onQueryUserFail(sender, args) {
alert('Failed to retrieve user name');
}
2. loadUserData
This function takes the given user.name and will get the property that is stored in property for that user. Here, in the success function, I am just outputting the result to an alert window:
function loadUserData(userName){
//Get Current Context
var clientContext = new SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Property to fetch from the User Profile
var strDepartment = window.property;
//If you are on On-Premise:
var targetUser = "BARDOM1\\" + userName;
//Create new instance of UserProfileProperty
departmentProperty = peopleManager.getUserProfilePropertyFor(targetUser, strDepartment)
//Execute the Query. (No load method necessary)
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
var messageText = window.property + " is " + departmentProperty .get_value();
alert(messageText);
}
function onFail(sender, args) {
alert("Error: " + args.get_message());
}
Finally, to actually run this process, we need to call GetCurrentUserProperty();. I put all of this code into a file called testproperty.js and saved it in SiteAssets. Then, on the page where we want the code to run, add a Content Editor Web Part and in edit -> path the call is ../../SiteAssets/testproperty.js. This will run once the page load - hope this helps anyone else who may be stuck on this!
I'm using Parse.com give people an ability to share a URL from the app, to an individual "object" in Parse.com.
The below code works fine- EXCEPT for some reason the "LINK" (URL) is not coming through. All the other data comes through.
Is there a trick with Parse and sharing URL's?
My HTML is fine, I"ve pasted my javascript below.
var url = document.URL;
var objectId = url.substr(url.lastIndexOf('/') + 1);
var name;
var designer;
var itemDescription;
var price;
var link;
var image;
Parse.initialize("xxx", "xxx");
var garmentsAPI = Parse.Object.extend("garmentsAPI");
var query = new Parse.Query(garmentsAPI);
query.get(objectId, {
success: function(garments) {
console.log("success");
name = garments.get("name");
designer = garments.get("designer");
itemDescription = garments.get("itemDescription");
price = garments.get("price");
link = garments.get("link");
image = garments.get("smallImage1");
$("#designer").html(designer);
$("#name").html(name);
$("#itemDescription").html(itemDescription);
$("#price").html(price);
$("#image").attr("src", image.url());
$("#buyButton").attr('href', link);
console.log(image.url());
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
console.log("fail");
}
});
if your column name of file is
smallImage1 then
you can get url of file is as follows:
smallImage1._url
I want to develop an app for Pebble. This app is going to tell you how long it takes from one place you set in options to another one taking in account traffic jams and stuff.
To achieve this I need to make a page that will return JSON. Pebble retrieves information using code like that:
var cityName = 'London';
var URL = 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName;
ajax(
{
url: URL,
type: 'json'
},
function(data) {
// Success!
console.log('Successfully fetched weather data!');
},
function(error) {
// Failure!
console.log('Failed fetching weather data: ' + error);
}
);
I created a small page with a js script that gets needed information from Yandex API:
var route;
ymaps.ready(init);
var myMap;
function init(){
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var time = 0;
var home = getParameterByName("h");
var work = getParameterByName("w");
ymaps.route([home, work],{avoidTrafficJams: true}).then(
function (router) {
route=router;
time = ((route.getTime())/60).toFixed(2);
var info = new Object;
info["home"] = home;
info["work"] = work;
info["time"] = ~~time+"m"+~~((time%1)*60)+"s";
JSON.stringify(info);
},
function (error) {
alert('Возникла ошибка: ' + error.message);
}
);
}
As you can see I can get a JSON string in the end. But how do I send it to clients when a request with right parameters is made?
I ended up using phantomjs and executing this js script on my php page.