Trying to get the user of a html page that resides in a SP document library. I tried doing something similar what is in this SO post but getting undefined. How can I get the user currently on the page? Thank you.
The function where I am trying to get the current user is $scope.updateTicket()
Below is the all of the JS code.
var app = angular.module('myApp', []);
var reports = [];
var areports = [];
var breports = [];
app.controller('myController',
function($scope, $http) {
$http({
method: 'GET',
url: ".../_api/web/lists/GetByTitle('tickets')/items?$top=1000&$select=ID,comments,ticket_number,status,date",
headers: {"Accept": "application/json;odata=verbose"}
}).success(function (data, status, headers, config) {
$scope.reports = data.d.results;
$scope.openModal = function() {
$getFormDigest = function() {
console.log("Inside getFormDigest...");
var formdigest;
jQuery.ajax({
url: "..._api/contextinfo",
type: "POST",
async: false,
headers: {
"accept": "application/json; odata=verbose",
type: "POST"
},
success: function(data)
{
formdigest = data.d.GetContextWebInformation.FormDigestValue
}
});
return formdigest;
}
$scope.updateFunc = function(itemID, new_comment) {
console.log('In update function...', itemID);
var formdigest = $scope.getFormDigest();
jQuery.ajax({
url: ".../_api/web/lists/GetByTitle('tickets')/items(" + itemID + ")",
type: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.Data.ticketsListItem' },
'comments': new_comment
}),
headers: {
"accept" : "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": formdigest,
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
},
success: function(data)
{
console.log("comments updated successfully...");
},
error: function(data)
{
console.log($("#__REQUESTDIGEST").val());
console.log("Error message: " + JSON.stringify(dta.responseJSON.error));
}
});
}
$scope.updateTicket = function() {
jQuery.ajax({
url: ".../_api/web/currentuser?select=Title",
type: "GET",
success: function(data)
{
var title = data.d.Title;
console.log(title);
},
error: function(data) {
console.log("Error occurred trying to get user Title");
}
});
var submitter = document.getElementById("submitter");
var context = SP.ClientContext.get_current();
var web = context.get_web();
var user = context.get_web().get_currentUser();
context.load(user);
console.log("User: " + web.get_currentUser().$5_0.$H_0.Title);
//var submitter = web.get_currentUser().$5_0.$H_0.Title;
var now = new Date();
var timestamp = (now.getUTCMonth() + 1 + "/" + now.getUTCDate() + "/" + now.getFullYear() + " " + ("0" + now.getUTCHours()).slice(-2) + ":" ("0" + now.getUTCMinutes()).slice(-2));
var temp = document.getElementById('comments').innerHTML;
temp += '<br>' + timestamp + ' -- ' + submitter + '<br>' + document.getElementById('comment-field').value + '<br>';
document.getElementById('comments').innerHTML = '<br>' + temp + '<br>';
$scope.updateFunc(document.getElementById('id').innerHTML, temp);
document.getElementById('comment-field').value = '';
document.getElementById('myModal').style.display = 'none';
location.reload();
};
modal.display = "block";
};
}).error(function(data, status, headers, config) {
console.log("an error occurred...");
});
var modal = document.getElementById('myModal');
var span = document.getElementByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if(event.target == modal) {
modal.style.display = "none";
}
}
});
In the head of my HTML file I'm pulling in the following SP libraries
init.js
MicrosoftAjax.js
sp.core.js
sp.runtime.js
sp.js
if we are talking about SharePoint OnPrem then You may always use _spPageContextInfo object which have many information about current context. In this object You also have the current user id and login in userId prop and userLoginName prop
Yep _spPageContextInfo.userDisplayName is all you need:
_spPageContextInfo.userDisplayName
_spPageContextInfo.userEmail
_spPageContextInfo.userId
_spPageContextInfo.isSiteAdmin
Related
I want to do live search and I need to use an id value from the first ajax call inside the second one.
I get the info when I type fast into the search, but if I search again or continue, I get this and the outer ajax wont be called again.
GET
http://api.themoviedb.org/3/movie/366924/videos?api_key=KEYHERE…9a6ebe&callback=jQuery1102017797202615180896_1472038138300&_=1472038138301
$('#movie-search')
.keyup(function() {
var input = $('#movie-search').val(),
movieName = encodeURI(input);
if (input.length > 3) {
$("#myList").empty();
$.ajax({
url: url + searchMode + apiKey + '&query=' + movieName,
dataType: 'jsonp',
success: function(data) {
console.log(data.results);
resultArray = data.results;
}
})
.then(function() {
$.each(resultArray,
function (index, value) {
console.log(value.id);
var searchVideo = 'movie/' + value.id + '/videos';
$.ajax({
url: url + searchVideo + apiKey,
dataType: 'jsonp',
success: function () {
$("#myList").append("stuffs");
}
});
});
});
}
$(this).change();
});
Try This -
$('#movie-search')
.keyup(function() {
var input = $('#movie-search').val();
var movieName = encodeURI(input);
if (input.length > 3) {
$("#myList").empty();
$.ajax({
url: url + searchMode + apiKey + '&query=' + movieName,
dataType: 'jsonp',
success: function(data) {
console.log(data.results);
resultArray = data.results;
$.each(resultArray,
function(index, value) {
console.log(value.id);
var searchVideo = 'movie/' + value.id + '/videos';
$.ajax({
url: url + searchVideo + apiKey,
dataType: 'jsonp',
success: function() {
$("#myList").append("stuffs");
}
});
});
}
});
}
$(this).change();
});
Please see the code below:
$.ajax({
type: "POST",
url: "Results1.aspx/TableQuery",
data: JSON.stringify({
mappingid: res[i],
strCon: $("#fieldGenieConnectionString")[0].value,
strTypeSession: $("#fieldTypeSession")[0].value
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i, res.length),
error: OnError,
failure: function (response) {
alert('there was a failure loading the webpage')
}
});
and the code below:
function OnSuccess(i, totalrows) {
return function (response) {
//if (response.d != "") {
var strResponse = response.d;
strResponse = strResponse.toUpperCase;
if (strResponse.indexOf("<TR>") > 0) {
// alert(response.d);
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
}
numSucceeded++;
var completeCalculation = (numSucceeded / totalrows) * 100
var rounded = completeCalculation.toFixed(0);
document.getElementById('ProgressIndicator').innerHTML = rounded + ' % complete';
document.getElementById('ProgressIndicator2').innerHTML = rounded + ' % complete';
if (numSucceeded === totalrows) {
var end = new Date().getTime();
var htmlResponse = "Loaded after: " + (end - start) / 1000 + " seconds"
document.getElementById('TotalTimeLabel').innerHTML = htmlResponse;
document.getElementById('TotalTime2Label').innerHTML = htmlResponse;
$("#LoadingImage").hide();
$("#LoadingImage2").hide();
}
}
}
The following line causes an error:
if (strResponse.indexOf("<TR>") > 0) {
strResponse = strResponse.toUpperCase;
There is a typo here. I think you want to write strResponse = strResponse.toUpperCase();
You are assigning a function to strResponse instead of calling the toUpperCase() on the existing strResponse
Because SharePoint works async i cannot store the data from multiple lists in array's and access them later.
I need to use 3 lists because they contain data from employees, holidays, and more.
See my code below for more information.
Is there no easier way to work with SharePoint and multiple lists to get the data. I tried also with executequeryasync but i cannot find a working solution for multiple lists. Or to store the value of each list in an array or variable and use it in another function because it's async.
$(function () {
$('#title').html("Inloggen verlofaanvraag");
});
function inLoggen() {
var initialen = $('#initialen').val();
var wachtwoord = $('#wachtwoord').val();
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Lijst werknemers')/Items?$filter=wInitialen eq '" + initialen + "' and wWachtwoord eq '" + wachtwoord + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
var x = data.d.results;
var werknemers = data.d.results;
for (var i = 0; i < x.length; i++) {
rInitialen = x[i].wInitialen;
rWachtwoord = x[i].wWachtwoord;
rVolledigenaam = x[i].wVolledigenaam;
}
if (i === 0) {
alert("U hebt geen toegang tot deze pagina !");
}
else {
$('#title').html("Welkom " + rVolledigenaam);
$('#inlogform').hide();
persoonlijketellers(werknemers);
}
},
error: function (xhr) {
console.log(xhr.status + ': ' + xhr.statusText);
}
});
}
function persoonlijketellers(werknemers) {
var rId = werknemers[0].ID;
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Lijst persoonlijke tellers')/Items?$filter=pWerknemer eq '" + rId + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
var x = data.d.results;
var ptellers = data.d.results;
for (var i = 0; i < x.length; i++) {
}
wettelijkeverlofdagen(werknemers, ptellers);
},
error: function (xhr) {
console.log(xhr.status + ': ' + xhr.statusText);
}
});
}
function wettelijkeverlofdagen(werknemers, ptellers) {
var rId = ptellers[0].ID;
alert(rId);
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Lijst persoonlijke tellers')/Items?$filter=pWerknemer eq '" + rId + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
var x = data.d.results;
var ptellers = data.d.results;
for (var i = 0; i < x.length; i++) {
}
},
error: function (xhr) {
console.log(xhr.status + ': ' + xhr.statusText);
}
});
}
You can store the data from multiple lists in array and access them when all of your async calls are complete, you just need to use some sort of promise pattern.
jQuery's .when method is probably the most useful in a situation like this:
function SPData() {
function getJsonDataAsync(url) {
// returning the $.ajax object is what makes the next part work...
return $.ajax({
url: url,
method: "GET",
contentType: "application/json",
headers: {
accept: "application/json;odata=verbose"
}
});
}
var requestURI1 = _spPageContextInfo.webServerRelativeUrl + "/_api/lists/..."
var requestURI2 = _spPageContextInfo.webServerRelativeUrl + "/_api/lists/..."
var requestURI3 = _spPageContextInfo.webServerRelativeUrl + "/_api/lists/..."
var req1 = getJsonDataAsync(requestURI1);
var req2 = getJsonDataAsync(requestURI2);
var req3 = getJsonDataAsync(requestURI3);
// now we can do the next line, because req1/2/3 are actually deferreds
// being returned from $.ajax
jQuery.when(req1, req2, req3).done(function(resp1, resp2, resp3) {
/* do something with all of the requests here...
resp1/2/3 correspond to the responses from each call and are each an
array that looks like: [data, statusText, jqXHR], which means that your
data is in resp1[0], resp2[0], etc. */
});
If you want, you can also just assign the returned values to variables in a higher level context, then use individual jQuery deferreds so that you can be sure all of the calls have succeeded before you start working with the data...
...
var x1, x2, x3;
// use the .then(function() { ... }) pattern because we are just returning a
// deferred/promise from $.ajax
getJsonDataAsync(requestURI1).then(function(data) {
x1 = data;
getJsonDataAsync(requestURI2).then(function(data2) {
x2 = data2;
getJsonDataAsync(requestURI3).then(function(data3) {
x3 = data3;
// do something with x1, x2, and x3
});
});
});
}
Hi I am getting an error while implementing the following.
When I click on the "save" button in following code:
<td width="20%"> <input id="save" onClick="updateMouseInfo();" type="button" value="Save" /></td>
I want to call the mouse_id parameter from getMouseInfo() function to updateMouseInfo() and I am getting the error that mouse_id is undefined, so please help me with the solution.
function getMouseInfo(mouse_id)
{
var dataString = {auth_token: sessionStorage.auth_token, id: mouse_id};
var mh_url = MH_HOST + '/mice/get_mouse_info.json';
alert("Inside Mouse Get Info");
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{
//for (var info_count = 0, info_len = data.length; info_count < info_len; info_count++ );
//{
alert("Inside for loop");
//var mouse_info = data.cage.mice[info_count];
var ear_tag = document.getElementById("ear_tag");
var age = document.getElementById("age");
var genotype = document.getElementById("genotype");
var owner = document.getElementById("owner");
//var born = document.getElementById("born");
//var euthanize = document.getElementById("euthanize");
//var note = document.getElementById("note");
ear_tag.innerHTML = data[0].ear_tag;
age.innerHTML = data[0].age;
genotype.innerHTML = data[0].genotype_id;
owner.innerHTML = data[0].owner_id;
//born.innerHTML = data[0].dob;
//euthanize.innerHTML = data[0].dob;
//note.innerHTML = data[0].dob;
//}
},
error: function (data)
{
alert("fail");
}
});
}
//update mouse info
function updateMouseInfo(mouseid)
{
var ear_tag = $('#input_ear_tag').val();
var age = $('#input_age').val();
var genotype = $('#input_genotype').val();
var owner = $('#input_owner').val();
var dataString = {auth_token: sessionStorage.auth_token, id: mouseid, mouse:
{ear_tag: ear_tag, age: age,}};
var mh_url = MH_HOST + '/mice/update.json';
alert("Inside Mouse update Info");
console.log('Data String='+ dataString.auth_token + 'Mouse id=' + dataString.id);
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{
document.getElementById('ear_tag').innerHTML = "<div" + ear_tag + "'>" + ear_tag + "</div>";
document.getElementById('age').innerHTML = "<div" + age + "'>" + age + "</div>";
document.getElementById('genotype').innerHTML = "<div" + genotype + "'>" + genotype + "</div>";
document.getElementById('owner').innerHTML = "<div" + owner + "'>" + owner + "</div>";
},
error: function (data)
{
alert("fail");
}
});
}
I am getting the following error in the browser console.
m_id=99
Data String=pvHxzkr3cys1gEVJRpCDMouse id=undefined
Whereas the id should be 99 in the above case it is showing undefined.
You are calling the updateMouseInfo function in the following manner:
onClick="updateMouseInfo();"
if you want to have same mouseid value which is taken by getMouseInfo() function when you call updateMouseInfo(),you will have to globalize getMouseInfo()
Hope it works.
I'm creating a custom button in the MS CRM ribbon that create a record in an entity, (i'm using odata), this button lunch a JavaScript function that use 'GetGlobalContext' method to get the context, im facing the below problem:
The value of the property 'GetGlobalContext' is null or undefined
here is my sample code :
//Parameters
var ODataPath;
var serverUrl;
//add the below script to the page DOM
var imported = document.createElement('script');
imported.src = 'ClientGlobalContext.js.aspx';
document.getElementsByTagName('head')[0].appendChild(imported);
//On COnvert to case click
function OnConvertClick(message) {
alert(Xrm.Page.getAttribute(message).getValue());
var data = {
subject: Xrm.Page.getAttribute(message).getValue()
};
CreateCaseOffer("incident", data);
}
//create case from an activity
function CreateCaseOffer(EntityName, data) {
var context = GetGlobalContext(); //GetGlobalContext function exists in ClientGlobalContext.js.aspx
serverUrl = location.protocol + "//" + location.hostname + ":" + location.port + "/" + context.getOrgUniqueName();
ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var jsonCaseOffers = window.JSON.stringify(data);
if (jsonCaseOffers != null) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataPath + "/" + EntityName + "Set",
data: jsonCaseOffers,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
$.each(data, function (k, v) {
alert(k + " - " + v);
});
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
}
});
}
}
any suggestions ??
it works fine now with var
var context = Xrm.Page.context;
instead of
var context = GetGlobalContext();