Retrieve multiple using OData in CRM 2011 - javascript

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.

Related

what URL call this function?

have function like this:
this.rmSaveParam = function(index, value, responseMethod, errorMethod) {
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: this.destination_ + (updater.currentDevice_ ? "rmNewParam?uid=" + encodeURIComponent(updater.currentDevice_) + "&" : "rmNewParam?") + "newParamIndex=" + encodeURIComponent(index) + "&newParamValue=" + encodeURIComponent(value),
success: responseMethod,
error: errorMethod
});
return false;
}
this.destination_ = https://www.econet24.com/
updater.currentDevice_ = C6ZPLELPP36R45624503480
index = 56
value = 67
I try to guess how the URL will look like.
I try something like this but it's probably wrong (too much question marks?): "https://www.econet24.com/C6ZPLELPP36R45624503480rmNewParam?uid=C6ZPLELPP36R45624503480&rmNewParam?newParamIndex=56&newParamValue=67"
It's easy enough to figure out. No need to guess!
const destination = 'https://www.econet24.com/';
const currentDevice = 'C6ZPLELPP36R45624503480';
const index = 56;
const value = 67;
const url = destination
+ (currentDevice
? "rmNewParam?uid=" + encodeURIComponent(currentDevice) + "&"
: "rmNewParam?")
+ "newParamIndex=" + encodeURIComponent(index)
+ "&newParamValue=" + encodeURIComponent(value);
console.log(url);
There is a better, and much cleaner, way to do this.
this.rmSaveParam = function(index, value, responseMethod, errorMethod) {
const queryParams = {
newParamIndex: index,
newParamValue: value
};
if (updater.currentDevice_) {
queryParams.uid = updater.currentDevice_;
}
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: this.destination_ + rmNewParam,
data: queryParams,
success: responseMethod,
error: errorMethod
});
return false;
}
Notice the lack of encodeURIComponent, this is done for you automatically.

Nested ajax call with an value from the first into the seconds Ajax call's url

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

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

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 + "'";

using 'GetGlobalContext' in javascript web resource

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

Categories