Dynamics crm rest builder query for many to many relationship - javascript

I need to set a contract lookup field in crm based on the account selected and business unit. This is a many to many relationship in crm .The best way i can think to do this is to create 2 querys/api calls (using crm rest builder) to be able to do this based on the criteria. the first query accesses the intersect table (account-contract table)in order to return all contracts based on the account and the seconds needs to further filter the results by looping through all the results from the first query and do a count off all the contracts that match the business unit selected. the issue im having now is that, i used an array to push all the values from the first query to be able to loop in the second one. However the array i created is not reaching the for loop thus the second query is not executing
function populateContractLookup() {
var buisnessUnitId = getFieldValue("hc_businessunit");
var worksiteId = getFieldValue("hc_worksite")[0].id;
worksiteId = stripCurlies(worksiteId);
if (buisnessUnitId != null) {
buisnessUnitId = stripCurlies(buisnessUnitId[0].id);
var condition = "_hc_businessunit_value eq " + buisnessUnitId + " and";
}
else {
condition = "";
}//to be able to count the how many contracts that would hav gotten populated to contract lookup field
var validcontractid;
var contractCount = 0;
var contractArray = [];
//this query gets all contracts based on account
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/hc_account_contractset?$select=contractid&$filter=accountid eq " + worksiteId, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
// Xrm.Utility.alertDialog(results.value.length);
for (var i = 0; i < results.value.length; i++) {
var contractid = results.value[i]["contractid"];
// Xrm.Utility.alertDialog(contractid);
contractArray.push(contractid);
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}// Xrm.Utility.alertDialog(contractArray.length) prints to the screen here
};
req.send();
//query to furthr filter the above query to get all contracts based on the buisness unit
//Xrm.Utility.alertDialog(contractArray.length);//not printing to screen
for (var i = 0; i < contractArray.length; i++) {
Xrm.Utility.alertDialog("were in the loop"); //not reaching this loop
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/contracts?$select=contractid&$filter=contractid eq " + contractArray[i] + " and _hc_businessunit_value eq " + buisnessUnitId, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
Xrm.Utility.alertDialog(results.value.length);
for (var i = 0; i < results.value.length; i++) {
contractCount++;
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
}
}
.ANy ideas of why i cant access my arrary?

Your first request is asynchronous. The code after your first req.send() is executing immediately, whereas you need the result of your first request to have been returned before any other code executes.
You therefore need to wrap your second request, which is dependent on the result of the first, into a callback function. You then call this callback function in the success callback of your first request.
See this StackOverflow answer for information on callback functions.
As an aside, your second request won't work. You're trying to execute a request once per contract that was retrieved. What you want to do is build your OData filter by iterating over contractArray array and writing '(contractid eq ' + contractArray[i] + ') or' //...
As another aside, consider using a FetchXML aggregate to count records.
Your code might look something like this:
var buisnessUnitId = getFieldValue("hc_businessunit");
var worksiteId = getFieldValue("hc_worksite")[0].id;
function populateContractLookup() {
worksiteId = stripCurlies(worksiteId);
if (buisnessUnitId != null) {
buisnessUnitId = stripCurlies(buisnessUnitId[0].id);
var condition = "_hc_businessunit_value eq " + buisnessUnitId + " and";
}
else {
condition = "";
}//to be able to count the how many contracts that would hav gotten populated to contract lookup field
var validcontractid;
var contractCount = 0;
var contractArray = [];
//this query gets all contracts based on account
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/hc_account_contractset?$select=contractid&$filter=accountid eq " + worksiteId, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
// Xrm.Utility.alertDialog(results.value.length);
for (var i = 0; i < results.value.length; i++) {
var contractid = results.value[i]["contractid"];
// Xrm.Utility.alertDialog(contractid);
contractArray.push(contractid);
}
// Call your callback function.
countContracts(contractArray);
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}// Xrm.Utility.alertDialog(contractArray.length) prints to the screen here
};
req.send();
}
Your callback function (though as I've mentioned above this needs rewriting):
function countContracts(contractArray) {
for (var i = 0; i < contractArray.length; i++) {
Xrm.Utility.alertDialog("were in the loop"); //not reaching this loop
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/contracts?$select=contractid&$filter=contractid eq " + contractArray[i] + " and _hc_businessunit_value eq " + buisnessUnitId, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
Xrm.Utility.alertDialog(results.value.length);
for (var i = 0; i < results.value.length; i++) {
contractCount++;
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
}
}

You can try switching the first call as synchronous by changing the flag like below & the result ll be available immediately before the second call.
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/hc_account_contractset?$select=contractid&$filter=accountid eq " + worksiteId, false);

Related

How to Get Attribute Value of XMLHttpRequest in Results

I have the following Microsoft Dynamics related XMLHttpRequest javascript function, and is encountering issue when attemtping to retrieve the entity attributes of the returned records.
The record managed to be created even though the conditions should have blocked it. It is likely that my following statement caused the issue:
var result1 = results.results[0];
alert("result1: " + result1.id); //Not displayed
function DisableInvalidRecordCreation(context) {
var saveEvent = context.getEventArgs();
var idNumber= Xrm.Page.getAttribute("IDNumber").getValue();
var category= Xrm.Page.getAttribute("Category").getValue();
var id = Xrm.Page.data.entity.getId();
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/ccc_cases?$select=IDNumber&$filter=IDNumber eq '" + idNumber+ "' and statecode eq 0", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\",odata.maxpagesize=1");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
if (results.value.length > 0 && id == "") {
alert(results.value.length); //Displayed as 1
var result1 = results.results[0];
alert("result1: " + result1.id); //Not displayed
for (var i = 0; i < results.entities.length; i++) {
var returned_category= results.entities[i]["Category"];
alert(returned_category); //Not displayed
if (category == 100000003 && returned_category!= 100000003)
{
alert("Invalid record");
saveEvent.preventDefault();
}
}
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
}
This is happening because in your get request you are selecting only IDNumber field and not the one you desire like Category
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/ccc_cases?$select=IDNumber&$filter=IDNumber eq '" + idNumber+ "' and statecode eq 0", false);
Also it should not be var result1 = results.results[0];
rather it should be var result1 =results.value[0]
sample code snippet for reference
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
for (var i = 0; i < results.value.length; i++) {
var abc = results.value[i]["abc"];
var xyz = results.value[i]["xyz"];
var pqr = results.value[i]["pqr"];
var pqr_formatted = results.value[i]["pqr#OData.Community.Display.V1.FormattedValue"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}

How to ignore NULL Value in CRM lookup field?

I have the following code setup onLoad to generate a banner on a 'Shipment' record whenever the associated Account is marked as "Service Watch". The code currently functions, however it's generating an error alert "unable to get property '0' of undefined or null reference". This error occurs when the user is creating a new Shipment record, as the Account field doesn't have a value yet.
How can I configure the code to ignore a NULL value in the Account field?
function checkServiceWatch() {
try{
var account = Xrm.Page.getAttribute("cmm_account").getValue();
var accountid = account[0].id;
var formattedGuid = accountid.replace("}", "");
accountid = formattedGuid.replace("{", "");
// alert("Accountid: " + accountid); // does that ID have brackets around it?
// alert("Request: " + Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=cmm_servicewatch");
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=cmm_servicewatch", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function()
{
if (this.readyState === 4)
{
req.onreadystatechange = null;
if (this.status === 200)
{
var result = JSON.parse(this.response);
var serviceWatch = result["cmm_servicewatch"];
// alert("serviceWatch: " + serviceWatch);
if(serviceWatch) //set notification
{
Xrm.Page.ui.setFormNotification("This Account is currently under Service Watch","WARNING","1");
} // else
// {
// //Xrm.Page.ui.clearFormNotification("1");
// }
}
else
{
Xrm.Utility.alertDialog("Status: " + this.status + ", Text: " + this.statusText);
}
}
};
req.send();
}
catch (err) {
alert("ServiceWatchCheckRibbon | checkServiceWatch " + err.message);
}
}
Should ignore records being created, but generate a banner on existing Shipments with Account values.
You have to check that the account variable has been initialised correctly. If it has, returning the variable will be equivalent to true and if it doesn't exist it will return false and not run the rest of the code in the try section. Correct code is below:
function checkServiceWatch() {
try{
var account = Xrm.Page.getAttribute("cmm_account").getValue();
if(account) {
var accountid = account[0].id;
var formattedGuid = accountid.replace("}", "");
accountid = formattedGuid.replace("{", "");
// alert("Accountid: " + accountid); // does that ID have brackets around it?
// alert("Request: " + Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=cmm_servicewatch");
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=cmm_servicewatch", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function()
{
if (this.readyState === 4)
{
req.onreadystatechange = null;
if (this.status === 200)
{
var result = JSON.parse(this.response);
var serviceWatch = result["cmm_servicewatch"];
// alert("serviceWatch: " + serviceWatch);
if(serviceWatch) //set notification
{
Xrm.Page.ui.setFormNotification("This Account is currently under Service Watch","WARNING","1");
} // else
// {
// //Xrm.Page.ui.clearFormNotification("1");
// }
}
else
{
Xrm.Utility.alertDialog("Status: " + this.status + ", Text: " + this.statusText);
}
}
};
req.send();
}
}
catch (err) {
alert("ServiceWatchCheckRibbon | checkServiceWatch " + err.message);
}
}
Assuming that account will hold an array and account id is not 0
You can either use length property to check if the account exist. If Yes then proceed else you can return
var account = Xrm.Page.getAttribute("cmm_account").getValue();
var accountid = account.length && account[0].id;
if(!accountid) return;
this Line will return the id into accountid if exist else returns 0
var accountid = account.length && account[0].id;
you can also add an additional check if you are not sure id exist in first element of account (account[0]) by adding
var accountid = account.length && (account[0] || {}).id;
which will return you undefined if you have elements in your account variable with the absence of key id
Only when account exist accountid variable will hold the account id if not it will have 0 or undefined which can be handled accordingly if you like to proceed or not.
Please let me know if I have solved your problem.
I will be doing like this always. Simply use this to do null check, stop execution & return.
var account = Xrm.Page.getAttribute("cmm_account").getValue();
var accountid;
if(account != null)
accountid = account[0].id.replace("}", "").replace("{", "");
else
return;
Please be aware that Xrm.Page is deprecated and will be replaced by the newer ExecutionContext. More information can be found at https://learn.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/execution-context
I've modified the relevant part of your code to the new ExecutionContext, but you can still use the Xrm.Page library in case you don't want to switch (yet).
function checkServiceWatch(executionContext) {
var formContext = executionContext.getFormContext();
var account = formContext.getAttribute("cmm_account").getValue();
if (!account) {
return;
}
var accountid = account[0].id;
// removed further code for brevity.
}
The if (!account) statement checks whether the account does not have an undefined or null value. The boolean statement works as null and undefined (along with NaN, 0 and empty strings) will resolve to false in a boolean context.

Dynamics 365 REST Builder - RouteTo function not working

I am trying to use RouteTo function through Dynamics CRM REST Builder Tool. When I am trying to execute this request, getting a data type error.
JSON Sent in request:
{"Target":{"primarykeyid":"{304CEAA4-B748-E811-A950-000D3A3606DE}","#odata.type":"Microsoft.Dynamics.CRM.systemuser"},"QueueItem":{"primarykeyid":"{976af0fa-9712-e911-a981-000d3a360e00}","#odata.type":"Microsoft.Dynamics.CRM.queueitem"}}
Error Message:
{"error":{"code":"0x0","message":"An error occurred while validating input parameters: Microsoft.OData.ODataException: Does not support untyped value in non-open type.\r\n at System.Web.OData.Formatter.Deserialization.DeserializationHelpers.ApplyProperty(ODataProperty property, IEdmStructuredTypeReference resourceType, Object resource, ODataDeserializerProvider deserializerProvider, ODataDeserializerContext readContext)\r\n at System.Web.OData.Formatter.Deserialization.ODataResourceDeserializer.ApplyStructuralProperties(Object resource, ODataResourceWrapper resourceWrapper, IEdmStructuredTypeReference structuredType, ODataDeserializerContext readContext)\r\n at Microsoft.Crm.Extensibility.CrmODataEntityDeserializer.ApplyStructuralProperties(Object resource, ODataResourceWrapper resourceWrapper, IEdmStructuredTypeReference structuredType, ODataDeserializerContext readContext)\r\n at System.Web.OData.Formatter.Deserialization.ODataResourceDeserializer.ReadResource(ODataResourceWrapper resourceWrapper, IEdmStructuredTypeReference structuredType, ODataDeserializerContext readContext)\r\n at System.Web.OData.Formatter.Deserialization.ODataResourceDeserializer.ReadResource(ODataResourceWrapper resourceWrapper, IEdmStructuredTypeReference structuredType, ODataDeserializerContext readContext)\r\n at Microsoft.Crm.Extensibility.ODataV4.CrmODataActionPayloadDeserializer.ReadEntry(ODataDeserializerContext readContext, ODataParameterReader reader, IEdmOperationParameter parameter)\r\n at Microsoft.Crm.Extensibility.ODataV4.CrmODataActionPayloadDeserializer.Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext
I already tried capitalizing the schema names, adding/removing {} brackets around GUIDs.
function route() {
var parameters = {};
var target = {};
target.primarykeyid = "304CEAA4-B748-E811-A950-000D3A3606DE";
target["#odata.type"] = "Microsoft.Dynamics.CRM.systemuser";
parameters.Target = target;
var queueitem = {};
queueitem.primarykeyid = "976af0fa-9712-e911-a981-000d3a360e00";
queueitem["#odata.type"] = "Microsoft.Dynamics.CRM.queueitem";
parameters.QueueItem = queueitem;
var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/RouteTo", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 204) {
//Success - No Return Data - Do Something
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send(JSON.stringify(parameters));
}
This request should be executed successfully.
I believe you want your QueueItem to have a queueitemid property (not a primarykeyid).
var parameters = {};
var target = {};
target.primarykeyid = "304CEAA4-B748-E811-A950-000D3A3606DE";
target["#odata.type"] = "Microsoft.Dynamics.CRM.systemuser";
parameters.Target = target;
var queueitem = {};
queueitem.queueitemid = "976af0fa-9712-e911-a981-000d3a360e00";
queueitem["#odata.type"] = "Microsoft.Dynamics.CRM.queueitem";
parameters.QueueItem = queueitem;
var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/RouteTo", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 204) {
//Success - No Return Data - Do Something
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send(JSON.stringify(parameters));

not able to get result length from ms crm web api call output in js

Below is my code snippet. I am trying to fetch all the Referenced Entities from ManyToOne Relationship of Annotation entity. In the result, I am able to get the object but when I'm trying to get the length of it, its giving "undefined". Please provide your valuable suggestions on this and how can we assign the Referenced Entity to a variable from result.
OR
is there any possibility to retrieve all the entities that are associated with Annotation entity, using Web API Call ( Dynamics 365).
function fetchIt()
{
var req = new XMLHttpRequest();
var webAPICall = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/EntityDefinitions(LogicalName='annotation')?$select=LogicalName&$expand=ManyToOneRelationships($select=ReferencedEntity)";
req.open("GET", webAPICall, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function ()
{
if (this.readyState === 4)
{
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
alert("results.valuelength: " +results.value.length);
for (var i = 0; i < results.value.length; i++)
{
var referencedEntity = results.value[i]["ReferencedEntity"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
}
You have two problems
You never send your request. You're missing req.send()
It won't be results.value it will be results.ManyToOneRelationships
Then it will work
Missed a small thing there. Instead of value, to check the length, we need to use ManyToOneRelationships (results.ManyToOneRelationships.length). Thank You.
var req = new XMLHttpRequest();
var webAPICall = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/EntityDefinitions(LogicalName='annotation')?$select=LogicalName&$expand=ManyToOneRelationships($select=ReferencedEntity)";
//alert(webAPICall);
req.open("GET", webAPICall, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function ()
{
if (this.readyState === 4)
{
req.onreadystatechange = null;
if (this.status === 200)
{
var results = JSON.parse(this.response);
alert("Results length: " + results.ManyToOneRelationships.length);
for (var i = 0; i < results.ManyToOneRelationships.length; i++)
{
var referencedEntity = results.ManyToOneRelationships[i]["ReferencedEntity"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();

Returning the XML received on readystatechange - JavaScript

This is my first post here on Stack. I am trying to make a Get request which is succeeding but I am having trouble getting the responseXML into a variable for processing. I think I am supposed to be using a callback function, but I still can't get it quite right. I am hopeful that somebody can point me in the correct direction. Code below.
<script type="text/javascript">
function buildOptions() {
var data = null;
/*xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
callback.call(xhr.responseXML);
}
});*/ //This code block worked, but I couldn't figure out how to get the result back
getXML = function(callback) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
}
}
function XMLCallBack(data) {
alert(data); // These two functions were the most recent attempt but I'm still missing something
}
xmlDoc = getXML(XMLCallBack); // this is supposed to start the processing of the returned XML
console.log(xmlDoc);
var campaignName = xmlDoc.getElementsByTagName('self')[0]; //XMLDoc contains a null variable when I get to this line
console.log(campaignName);
var campaigns = ["","Freshman Campaign","Sophomore Campaign","Junior Campaign","Senior Campaign"]; //Code from here and below will be changing slightly once I can get XMLDoc to be correct
var sel = document.getElementById('campaignList');
for(var i = 0; i < campaigns.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = campaigns[i];
opt.value = campaigns[i];
sel.appendChild(opt);
}
}
</script>
I believe you should move open ---> send outside the onreadystatechange, like this:
getXML = function(callback) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
}
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
}
EDIT: This code should work:
<script type="text/javascript">
function buildOptions() {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = XMLCallBack;
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
function XMLCallBack() {
if (xhr.readyState == 4 && xhr.status == 200) {
xmlDoc = xhr.responseText;
var campaignName = xmlDoc.getElementsByTagName('self')[0];
var campaigns = ["","Freshman Campaign","Sophomore Campaign","Junior Campaign","Senior Campaign"];
var sel = document.getElementById('campaignList');
for(var i = 0; i < campaigns.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = campaigns[i];
opt.value = campaigns[i];
sel.appendChild(opt);
}
}
}
}
</script>
I haven't tried it so I might have made some mistakes. If you want to, you can move XMLCallBack() outside of buildOptions() and use this.readyState, this.status and this.responseText instead of xhr.readyState etc..

Categories

Resources