using 'GetGlobalContext' in javascript web resource - javascript

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

Related

Trying to get current user of SharePoint Page

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

Retrieve multiple using OData in CRM 2011

I want to retrieve multiple record. Here is my code;
function GetQuoteDetails(quoteId) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataSetName = "QuoteDetailSet";
var odataSelect = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "$filter=QuoteId/Id eq guid'" + quoteId + "'";
var jSonArray = new Array();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null) {
jSonArray.push(data.d);
}
},
});
return jSonArray;
}
It returns nothing. But there should be 4 records returned. Where is the problem?
Since this is Asynchronous call, you cannot return from function GetQuoteDetails. For verification either use Console.log or alert to check what is data.d value.

Rest API Multiple Lists in SharePoint

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

populated jquery objects show as undefined when passed

In the following script, although the two weather objects are both populated with data in the ajax calls, the updateWeather call shows them both as undefined prior to that line executing. I moved the variable declarations so they would be global but they still both show undefined prior to the updateWeather call. What am I missing? Can I not set up a variable in the ajax success function and then pass it later?
Note: If you want to test this use a different url as this one won't work for you with out my credentials
function getWeatherForecastStationCode() {
var d = new Date();
var parts = d.toString().split(" ");
var dDate = parts[1] + " " + parts[2] + ", " + parts[3];
var ampm;
if (parts[4].split(":")[0] <= 12) {
ampm = "AM";
} else {
ampm = "PM";
}
var dtime = parts[4].split(":")[0] + ":" + parts[4].split(":")[1];
var datetime = dDate + " " + dtime + ampm;
alert(datetime);
var weatherStation = "KPBI"; // get from GetWeatherService.svc
var forecastFields = "&fields=periods.maxTempF%2cperiods.minTempF%2cperiods.vaildTime%2cperiods.weather%2cperiods.icon";
var currentFields = "&fields=ob.tempC%2cob.tempF%2cob.icon%2cplace.name%2cplace.state";
var forecastUrlWeatherStation = 'http://api.aerisapi.com/forecasts/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + forecastFields;
var currentUrlWeatherStation = 'http://api.aerisapi.com/observations/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + currentFields;
$.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
forecastedWeather = {
weather: json.response[0].periods[0].weather,
maxTemp: json.response[0].periods[0].maxTempF,
minTemp: json.response[0].periods[0].minTempF,
weatherIcon: json.response[0].periods[0].icon,
obsTime: datetime
};
}
else {
alert('An error occurred: ' + json.error.description);
}
}
});
var location;
$.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
var place = json.response.place.name.split(" ");
if (place.length === 1) {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length);
} else {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length) + " " + place[1].charAt(0).toUpperCase() + place[1].substr(1, place[1].length) + ", " + json.response.place.state.toUpperCase();
}
currentWeather = {
location: location,
currentTemp: json.response.ob.tempF
};
} else {
alert('An error occurred: ' + json.error.description);
}
}
});
updateWeather(forecastedWeather,currentWeather);
}
The problem is that AJAX is Asynchronous (Thats the "A" in "AJAX"), so the call to updateWeather is executing before a response is received from your 2 ajax calls.
The way to do this then, is to wait for all ajax calls to complete before calling updateWeather.
Something like the following (untested):
$.when(getForecast(),getCurrent()).done(function(f,c){
updateWeather(forecastedWeather,currentWeather)
});
function getForecast(){
return $.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json"
....
});
};
function getCurrent(){
return $.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json"
....
});
};

Retrieving Multiple Records OData java Scripts Microsoft Dynamics CRM

I am using the following java script code to retrieve contacts by account Id. I am set setting the alert message debugging. It does not enter in success call back message function.
Ending up with following error
Error while retrieval
"error" : { "lang":"en-US", "Value":"Syntax error'\ufffd' at position 20." }
I am using the following code.
function retrieveMultiple(odataSetName, select, filter, successCallback) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "?";
alert("retrieveMultiple"+odataUri);
if (select) {
odataUri += "$select=" + select + "&";
alert("select error="+odataUri);
}
if (filter) {
odataUri += "$filter=" + filter;
alert("filter error="+odataUri);
}
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataUri,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
var x = XMLHttpRequest.setRequestHeader("Accept", "application/json");
alert(" in Ajax :beforeSend:" + x );
},
success: function (data, textStatus, XmlHttpRequest) {
alert("In success function outside success");
if (successCallback) {
alert("successCallback in if");
if (data && data.d && data.d.results) {
alert("data && data.d && data.d.results"+data + data.d + data.d.results);
successCallback(data.d.results, textStatus, XmlHttpRequest);
alert("data.d.results, textStatus, XmlHttpRequest" + data.d.results + textStatus + XmlHttpRequest);
}
else if (data && data.d) {
successCallback(data.d, textStatus, XmlHttpRequest);
}
else {
successCallback(data, textStatus, XmlHttpRequest);
}
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert(" In erro function");
if (XmlHttpRequest && XmlHttpRequest.responseText) {
alert(" In error function If");
alert("Error while retrieval ; Error – " + XmlHttpRequest.responseText);
}
}
});
}
function readRecordsOnSuccess(data, textStatus, XmlHttpRequest) {
// Loop through the retrieved records
for (var indx = 0; indx < data.length; indx++) {
alert("Name – " + data[indx].name);
}
}
function retrieveContactsByAccountId() {
// Pass ‘Contact’ set name since we are reading Contacts
var oDataSetName = "ContactSet";
// Column names of ‘Contact’ (Pass * to read all columns)
var columns = "FirstName";
// Read Account Guid
var accountId = Xrm.Page.data.entity.getId()
// Prepare filter
var filter = "AccountId/Id eq guid’" + accountId + "‘";
alert("retrieveContactsByAccountId"+filter);
retrieveMultiple(oDataSetName, columns, filter, readRecordsOnSuccess);
}
Looks like common mistype ;) Notice following string you are passing:
var filter = "AccountId/Id eq guid’" + accountId + "‘";
Your apostrophes are different from usual ones
You need to use regular '
var filter = "AccountId/Id eq guid'" + accountId + "'";

Categories