Created
December 6, 2016 14:27
-
-
Save justlikemichel/fa67bb412bc5e2882411ef35e362fbbd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Helper method for calling the WebApi | |
function callWebApi(method, collection, querystring, postData, successCallBack, errorCallBack) { | |
// Get the client Url | |
var clientUrl = Xrm.Page.context.getClientUrl(), | |
// Create a XMLHttpRequest | |
request = new XMLHttpRequest(); | |
// Build the request using the provided collection and querystring | |
request.open(method, clientUrl + "/api/data/v8.1/" + collection + (querystring || ""), true); | |
// Add the required headers for OData | |
request.setRequestHeader("Accept", "application/json"); | |
request.setRequestHeader("Content-Type", "application/json; charset=utf-8"); | |
request.setRequestHeader("OData-MaxVersion", "4.0"); | |
request.setRequestHeader("OData-Version", "4.0"); | |
// Bind the onload, which only fires when a XHR requests finishes (regardless of status) | |
request.onload = function () { | |
// Parse any response data we may have | |
var data = { }; | |
try { | |
data = JSON.parse(this.response); | |
} catch (err) { data = { }; } | |
// Check if returned status code is within the OK range | |
if (this.status >= 200 && this.status < 400) { | |
// Success! | |
// If status is 204, then a new record was created and we'll need to get it's ID | |
if (this.status == 204) data.OData_EntityId = this.getResponseHeader("OData-EntityId"); | |
// Call the successCallBack with the data that was returned | |
successCallBack(data); | |
} else { | |
// We reached our target server, but it returned an error | |
// Call the errorCallBack with the statuscode and any error returned by the Api | |
errorCallBack(this.status, typeof data.error != "undefined" ? data.error : null); | |
} | |
}; | |
request.onerror = function () { | |
// There was a connection error of some sort, call the errorCallBack | |
errorCallBack(); | |
}; | |
// If postdata was included, send that | |
if (!!postData) request.send(postData); | |
else request.send(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment