Sample code that demonstrates how to perform the most basic data operations using the Dynamics CRM OData endpoint and JavaScript. The sample has an interactive user interface that allows the user to search for Contacts by name. User can create, update and delete Contacts.
The sample uses the jQuery library for DOM access and manipulation. The sample also uses jQuery’s $.ajax method to make service calls to the OData endpoint.
Step3: Add the Following 1: N Relationship between Contact and Related Entity
<!DOCTYPE html>
<!--
// =====================================================================
// This file is part of the Microsoft Dynamics CRM SDK code samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// =====================================================================
-->
<html lang="en-us">
<head>
<title>REST JQuery Contact Editor</title>
<!-- /WebResources/ClientGlobalContext.js.aspx is accessed using a relative path
because the name of the Web Resource created from this file is "sample_/RESTJQueryContactEditor.htm".
The use of the backslash within the name creates a virtual folder that must be considered
in relative links between Web Resources.
-->
<script type="text/javascript" src="../ClientGlobalContext.js.aspx"></script>
<script src="Scripts/jquery_1.9.1.min.js"></script>
<script src="Scripts/RESTJQueryContactEditor.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
// <![CDATA[
//Variable to hold reference to a table row between ajax call and callback
var TMP_ROW = null;
//Clicks the search button when the document loads so that the first set of
// up to 50 records is retrieved.
$(document).ready(SearchButton_onclick);
//*************************** EVENT HANDLERS ******************************
//Search Button Event Handler
function SearchButton_onclick()
{
var searchValue = $("#txtSearch").val();
//Search where FullName contains search text
if (searchValue != "")
{
retrieveMultiple("ContactSet", "substringof('" +
searchValue + "',FullName)", SearchCompleted, null);
}
//Retrieve all Contacts
else
{
retrieveMultiple("ContactSet", null, SearchCompleted, null);
}
}
//New Button Event Handler
function NewButton_onclick()
{
//Create a new Contact object
var contact = CreateNewContact();
//Add a new row to the table using this Contact.
CreateNewRow(contact, true);
}
//*************************** CALLBACK FUNCTIONS ******************************
//Callback - Search Success
function SearchCompleted(data, textStatus, XmlHttpRequest)
{
//Clear out all Contacts in the grid.
EmptyTable();
//Re-populate the grid with results, if any
if (data && data.length > 0)
{
//Hide the empty message
HideEmptyRow();
for (var i = 0; i < data.length; i++)
{
//Generates all the HTML for a new row and populates
//it with data based on the Contact object
CreateNewRow(data[i]);
}
alert(data.length + " Contact record(s) retrieved.");
}
//Or display the empty table message if no results
else
{
ShowEmptyRow();
alert("No Contact record(s) retrieved.");
}
}
//Callback - Delete Success
function DeleteContactCompleted(data, textStatus, XmlHttpRequest)
{
alert("Contact deleted.");
}
//Callback - Delete Failure
function DeleteContactErrored(data, textStatus, errorThrown)
{
alert("Failed to delete Contact.");
}
//Callback - Update Success
function ContactUpdateCompleted(data, textStatus, XmlHttpRequest)
{
TMP_ROW = null;
//Enable all buttons
$(":button").attr('disabled', '');
alert("Update complete.");
}
//Callback - Create Success
function ContactCreateCompleted(data, textStatus, XmlHttpRequest)
{
//Update the Contact row with the ContactId so future user actions
//on this row operate correctly. (Update vs. Create)
if (TMP_ROW && data && data.ContactId)
{
//Set the ContactId
$(TMP_ROW).find("#ContactId").attr("value", data.ContactId);
//Set the Link column
$(TMP_ROW).find("#RecordLink").html("<a target=\"_blank\" href=\"" +
clientUrl + "/main.aspx?etn=contact&id=%7b" + data.ContactId +
"%7d&pagetype=entityrecord\">View</a>");
}
//Enable all buttons
$(":button").attr('disabled', '');
TMP_ROW = null;
alert("Create complete.");
}
//Callback - Create Failure
function ContactCreateFailed(data, textStatus, errorThrown)
{
//Enable all buttons
$(":button").removeAttr("disabled");
TMP_ROW = null;
alert("Failed to create Contact...");
}
//*************************** HELPER FUNCTIONS ******************************
//Accepts a contact object, generates a new row in the table,
//and wires up event handlers for buttons in the row
function CreateNewRow(contact, fromNewButton)
{
if (contact)
{
//Hide the "Empty Message" row
$("TR.EmptyRow").hide();
//Generate a new row
;
var row = $("<tr class='RecordRow' />");
row.append($("<td><span id='RecordLink'>N/A</span></td>"));
row.append($("<td><input type='text' id='FirstName' style='width: 100px;' /></td>"));
row.append($("<td><input type='text' id='LastName' style='width: 100px;' /></td>"));
row.append($("<td><input type='text' id='Telephone1' style='width: 70px;' /></td>"));
row.append($("<td><input type='text' id='EMailAddress1' style='width: 100px;' /></td>"));
row.append($("<td><input type='text' id='Address1_Line1' style='width: 100px;' /></td>"));
row.append($("<td><input type='text' id='Address1_City' style='width: 70px;' /></td>"));
row.append($("<td><input type='text' id='Address1_StateOrProvince' style='width: 60px;' /></td>"));
row.append($("<td><input type='text' id='Address1_PostalCode' style='width: 50px;' /></td>"));
row.append($("<td><input type='button' id='SaveButton' title='Click to save changes to the record.' style='width: 50px; margin-left: 5px;' value='Save' /></td>"));
row.append($("<td><input type='button' id='DeleteButton' title='Click to remove the record from the system.' style='width: 50px; margin-left: 5px;' value='Delete' /></td>"));
row.append($("<td style='display: none'><input type='text' id='ContactId' /></td>"));
if (fromNewButton && $("#ContactTableBody").children().first())
{
//Add it to the top
$("#ContactTableBody").children().first().before(row);
}
else
{
//Add it to the bottom
$("#ContactTableBody").append(row);
}
//Set table fields from contact
if (contact.ContactId)
{
row.find("#ContactId").attr("value", contact.ContactId);
//Set the Link column
row.find("#RecordLink").html("<a target=\"_blank\" href=\"" +
clientUrl + "/main.aspx?etn=contact&id=%7b" + contact.ContactId +
"%7d&pagetype=entityrecord\">View</a>");
}
if (contact.FirstName)
row.find("#FirstName").attr("value", contact.FirstName);
if (contact.LastName)
row.find("#LastName").attr("value", contact.LastName);
if (contact.Telephone1)
row.find("#Telephone1").attr("value", contact.Telephone1);
if (contact.EMailAddress1)
row.find("#EMailAddress1").attr("value", contact.EMailAddress1);
if (contact.Address1_Line1)
row.find("#Address1_Line1").attr("value", contact.Address1_Line1);
if (contact.Address1_City)
row.find("#Address1_City").attr("value", contact.Address1_City);
if (contact.Address1_StateOrProvince)
row.find("#Address1_StateOrProvince").attr("value", contact.Address1_StateOrProvince);
if (contact.Address1_PostalCode)
row.find("#Address1_PostalCode").attr("value", contact.Address1_PostalCode);
//Wire up the SaveButton event handler
row.find("#SaveButton").click(function ()
{
//Figure out what row the SaveButton belongs to
var contactRow = $(this).parent().parent();
//Store the row in a temporary buffer so we know which to update in the callback method.
TMP_ROW = contactRow;
//Disable all buttons so the user can't invoke other actions
$(":button").attr('disabled', 'disabled');
//Create a new Contact object by extracting data from the row
var contactObject = ExtractContactFromRow(contactRow);
//The contactObject won't have a ContactId unless its stored in CRM already
if (contactObject.ContactId && contactObject.ContactId != null)
{
//Update the CRM record
updateRecord(contactObject.ContactId, contactObject, "ContactSet", ContactUpdateCompleted, null);
}
else
{
//Create the CRM record
createRecord(contactObject, "ContactSet", ContactCreateCompleted, ContactCreateFailed);
}
});
//Wire up the DeleteButton event handler
row.find("#DeleteButton").click(function ()
{
var confirmAnswer = confirm("Are you sure you want to delete this contact?");
if (confirmAnswer)
{
var contactRow = $(this).parent().parent();
//Store the row in a temporary buffer so we know which to update in the callback method.
TMP_ROW = contactRow;
//Create a new Contact object by extracting data from the row.
var contactObject = ExtractContactFromRow(contactRow);
//If the Contact has a ContactId, Delete it from CRM and delete the row
if (contactObject.ContactId && contactObject.ContactId != null)
{
//Delete the record from CRM
deleteRecord(contactObject.ContactId, "ContactSet", DeleteContactCompleted, null);
//Delete the Row
contactRow.remove();
}
//If no ContactId, only delete the row.
else
{
//Delete the Row
contactRow.remove();
}
}
});
}
}
//Accepts a row and returns a Contact object
function ExtractContactFromRow(row)
{
var contact = new Object();
//This 'if' statement is necessary because without it, if the Contact
//is passed to the createRecord function, the function will try to parse
//an empty Guid and fail upon Create
if (row.find("#ContactId").val())
{
contact.ContactId = row.find("#ContactId").val();
}
contact.FirstName = row.find("#FirstName").val();
contact.LastName = row.find("#LastName").val();
contact.Telephone1 = row.find("#Telephone1").val();
contact.EMailAddress1 = row.find("#EMailAddress1").val();
contact.Address1_Line1 = row.find("#Address1_Line1").val();
contact.Address1_City = row.find("#Address1_City").val();
contact.Address1_StateOrProvince = row.find("#Address1_StateOrProvince").val();
contact.Address1_PostalCode = row.find("#Address1_PostalCode").val();
return contact;
}
//Instantiates and returns an empty contact object
function CreateNewContact()
{
//Each of these contact fields are named as they appear in the Odata metadata.
var contact = new Object();
contact.FirstName = "Firstname";
contact.LastName = "Lastname";
contact.Telephone1 = null;
contact.EMailAddress1 = null;
contact.Address1_Line1 = null;
contact.Address1_City = null;
contact.Address1_StateOrProvince = null;
contact.Address1_PostalCode = null;
contact.ContactId = null;
return contact;
}
//Hides the row with the empty message in Contacts table
function HideEmptyRow()
{
if ($("TR.EmptyRow")[0])
{
$("TR.EmptyRow").hide();
}
}
//Shows the row with the empty message in Contacts table
function ShowEmptyRow()
{
if ($("TR.EmptyRow")[0])
{
$("TR.EmptyRow").show();
}
else
{
var emptyRow = $("<tr id='EmptyRow' class='EmptyRow'><td colspan='12' style='text-align:center;'><span>No Contact records are available in this view.</span></td></tr>")
$("#ContactTableBody").append(emptyRow);
}
}
//Removes all the Contact rows from the table
function EmptyTable()
{
//Clear out the Contact table's rows that have attribute class=RecordRow
//These are the ones that contain Contact record data.
$("TR.RecordRow").remove();
}
// ]]>
</script>
<style type="text/css">
#ContactTable {
border: none;
border-spacing: 0px;
border-width: 0px;
font-family: Arial;
font-size: 10;
margin-top: 10px;
border-collapse: collapse;
table-layout: auto;
}
#ContactTable td {
border-width: 1px;
border-style: none;
margin: 1px;
}
#ContactTable th {
border-width: 1px;
padding: 1px;
border-style: none;
margin: 1px;
font-family: Arial;
}
#ContactTable INPUT[type="text"] {
border-width: 1px;
padding: 1px;
border-style: none;
margin: 0;
}
#ContactTable INPUT[type="button"] {
border-width: 1px;
border-style: outset;
}
body {
background: lightblue;
font-family: Segoe UI;
}
</style>
</head>
<body>
<h1>REST JQuery Contact Editor Sample</h1>
<p>
This page requires JavaScript and will update dynamically.
</p>
<h3 style="font-family: Arial;">
Search for Contacts by Name
</h3>
<div>
<label for="txtSearch" style="font-family: Arial;">
Name:
</label>
<input type="text" style="width: 200px;" id="txtSearch" />
<input type="button" id="SearchButton" value="Search" title="Click to search contacts by name" style="width: 80px;" onclick="return SearchButton_onclick()" />
<input type="button" id="NewButton" value="New Contact" title="Click to create new contact record" style="width: 90px;" onclick="return NewButton_onclick()" />
</div>
<div>
<table id="ContactTable" summary="This table displays contact records with respective actions to view, update, delete each record.">
<thead>
<tr>
<th />
<th scope="col">
First Name
</th>
<th scope="col">
Last Name
</th>
<th scope="col">
Phone
</th>
<th scope="col">
Email
</th>
<th scope="col">
Street
</th>
<th scope="col">
City
</th>
<th scope="col">
State
</th>
<th scope="col">
ZIP
</th>
<th scope="col">
Save
</th>
<th scope="col">
Delete
</th>
<th style="display: none" scope="col">
ContactId
</th>
</tr>
</thead>
<tbody id="ContactTableBody"></tbody>
</table>
</div>
</body>
</html>
Step5: Add a JavaScript Web Resource sample_/Scripts/RESTJQueryContactEditor Like Below:-
// =====================================================================
// This file is part of the Microsoft Dynamics CRM SDK code samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// =====================================================================
/// <reference path="jquery-1.9.1.js" />
//GetGlobalContext function exists in ClientGlobalContext.js.aspx so the
//host HTML page must have a reference to ClientGlobalContext.js.aspx.
var context = GetGlobalContext();
//Retrieve the client url
var clientUrl = context.getClientUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
function createRecord(entityObject, odataSetName, successCallback, errorCallback)
{
/// <summary>
/// Uses jQuery's AJAX object to call the Microsoft Dynamics CRM OData endpoint to
/// Create a new record
/// </summary>
/// <param name="entityObject" type="Object" required="true">
/// 1: entity - a loose-type object representing an OData entity. any fields
/// on this object must be camel-cased and named exactly as they
/// appear in entity metadata
/// </param>
/// <param name="odataSetName" type="string" required="true">
/// 1: set - a string representing an OData Set. OData provides uri access
/// to any CRM entity collection. examples: AccountSet, ContactSet,
/// OpportunitySet.
/// </param>
/// <param name="successCallback" type="function" >
/// 1: callback-a function that can be supplied as a callback upon success
/// of the ajax invocation.
/// </param>
/// <param name="errorCallback" type="function" >
/// 1: callback-a function that can be supplied as a callback upon error
/// of the ajax invocation.
/// </param>
//entityObject is required
if (!entityObject)
{
alert("entityObject is required.");
return;
}
//odataSetName is required, i.e. "AccountSet"
if (!odataSetName)
{
alert("odataSetName is required.");
return;
}
else
{ odataSetName = encodeURIComponent(odataSetName); }
//Parse the entity object into JSON
var jsonEntity = window.JSON.stringify(entityObject);
//Asynchronous AJAX function to Create a CRM record using OData
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: clientUrl + ODATA_ENDPOINT + "/" + odataSetName,
data: jsonEntity,
beforeSend: function (XMLHttpRequest)
{
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest)
{
if (successCallback)
{
successCallback(data.d, textStatus, XmlHttpRequest);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown)
{
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
errorHandler(XmlHttpRequest, textStatus, errorThrown);
}
});
}
function retrieveRecord(id, odataSetName, successCallback, errorCallback)
{
/// <summary>
/// Uses jQuery's AJAX object to call the Microsoft Dynamics CRM OData endpoint to
/// retrieve an existing record
/// </summary>
/// <param name="id" type="guid" required="true">
/// 1: id - the guid (primarykey) of the record to be retrieved
/// </param>
/// <param name="odataSetName" type="string" required="true">
/// 1: set - a string representing an OData Set. OData provides uri access
/// to any CRM entity collection. examples: AccountSet, ContactSet,
/// OpportunitySet.
/// </param>
/// <param name="successCallback" type="function" >
/// 1: callback-a function that can be supplied as a callback upon success
/// of the ajax invocation.
/// </param>
/// <param name="errorCallback" type="function" >
/// 1: callback-a function that can be supplied as a callback upon error
/// of the ajax invocation.
/// </param>
//id is required
if (!id)
{
alert("record id is required.");
return;
}
else
{
id = encodeURIComponent(id);
}
//odataSetName is required, i.e. "AccountSet"
if (!odataSetName)
{
alert("odataSetName is required.");
return;
}
else
{ odataSetName = encodeURIComponent(odataSetName); }
//Asynchronous AJAX function to Retrieve a CRM record using OData
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: clientUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
beforeSend: function (XMLHttpRequest)
{
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest)
{
if (successCallback)
{
successCallback(data.d, textStatus, XmlHttpRequest);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown)
{
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
errorHandler(XmlHttpRequest, textStatus, errorThrown);
}
});
}
function retrieveMultiple(odataSetName, filter, successCallback, errorCallback)
{
/// <summary>
/// Uses jQuery's AJAX object to call the Microsoft Dynamics CRM OData endpoint to
/// Retrieve multiple records
/// </summary>
/// <param name="odataSetName" type="string" required="true">
/// 1: set - a string representing an OData Set. OData provides uri access
/// to any CRM entity collection. examples: AccountSet, ContactSet,
/// OpportunitySet.
/// </param>
/// <param name="filter" type="string">
/// 1: filter - a string representing the filter that is appended to the odatasetname
/// of the OData URI.
/// </param>
/// <param name="successCallback" type="function" >
/// 1: callback-a function that can be supplied as a callback upon success
/// of the ajax invocation.
/// </param>
/// <param name="errorCallback" type="function" >
/// 1: callback-a function that can be supplied as a callback upon error
/// of the ajax invocation.
/// </param>
//odataSetName is required, i.e. "AccountSet"
if (!odataSetName)
{
alert("odataSetName is required.");
return;
}
else
{ odataSetName = encodeURIComponent(odataSetName); }
//Build the URI
var odataUri = clientUrl + ODATA_ENDPOINT + "/" + odataSetName;
//If a filter is supplied, append it to the OData URI
if (filter)
{
odataUri += "?$filter=" + encodeURIComponent(filter);
}
//Asynchronous AJAX function to Retrieve CRM records using OData
$.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.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest)
{
if (successCallback)
{
if (data && data.d && data.d.results)
{
successCallback(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)
{
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
errorHandler(XmlHttpRequest, textStatus, errorThrown);
}
});
}
function updateRecord(id, entityObject, odataSetName, successCallback, errorCallback)
{
/// <summary>
/// Uses jQuery's AJAX object to call the Microsoft Dynamics CRM OData endpoint to
/// update an existing record
/// </summary>
/// <param name="id" type="guid" required="true">
/// 1: id - the guid (primarykey) of the record to be retrieved
/// </param>
/// <param name="entityObject" type="Object" required="true">
/// 1: entity - a loose-type object representing an OData entity. any fields
/// on this object must be camel-cased and named exactly as they
/// appear in entity metadata
/// </param>
/// <param name="odataSetName" type="string" required="true">
/// 1: set - a string representing an OData Set. OData provides uri access
/// to any CRM entity collection. examples: AccountSet, ContactSet,
/// OpportunitySet.
/// </param>
/// <param name="successCallback" type="function" >
/// 1: callback-a function that can be supplied as a callback upon success
/// of the ajax invocation.
/// </param>
/// <param name="errorCallback" type="function" >
/// 1: callback-a function that can be supplied as a callback upon error
/// of the ajax invocation.
/// </param>
//id is required
if (!id)
{
alert("record id is required.");
return;
}
else
{ id = encodeURIComponent(id); }
//odataSetName is required, i.e. "AccountSet"
if (!odataSetName)
{
alert("odataSetName is required.");
return;
}
else
{ odataSetName = encodeURIComponent(odataSetName); }
if (!entityObject)
{
alert("entityObject is required.");
return;
}
//Parse the entity object into JSON
var jsonEntity = window.JSON.stringify(entityObject);
//Asynchronous AJAX function to Update a CRM record using OData
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: jsonEntity,
url: clientUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
beforeSend: function (XMLHttpRequest)
{
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
//Specify the HTTP method MERGE to update just the changes you are submitting.
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
success: function (data, textStatus, XmlHttpRequest)
{
//The MERGE does not return any data at all, so we'll add the id
//onto the data object so it can be leveraged in a Callback. When data
//is used in the callback function, the field will be named generically, "id"
data = new Object();
data.id = id;
if (successCallback)
{
successCallback(data, textStatus, XmlHttpRequest);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown)
{
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
errorHandler(XmlHttpRequest, textStatus, errorThrown);
}
});
}
function deleteRecord(id, odataSetName, successCallback, errorCallback)
{
/// <summary>
/// Uses jQuery's AJAX object to call the Microsoft Dynamics CRM OData endpoint to
/// delete an existing record
/// </summary>
/// <param name="id" type="guid" required="true">
/// 1: id - the guid (primarykey) of the record to be retrieved
/// </param>
/// <param name="odataSetName" type="string" required="true">
/// 1: set - a string representing an OData Set. OData provides uri access
/// to any CRM entity collection. examples: AccountSet, ContactSet,
/// OpportunitySet.
/// </param>
/// <param name="successCallback" type="function" >
/// 1: callback-a function that can be supplied as a callback upon success
/// of the ajax invocation.
/// </param>
/// <param name="errorCallback" type="function" >
/// 1: callback-a function that can be supplied as a callback upon error
/// of the ajax invocation.
/// </param>
//id is required
if (!id)
{
alert("record id is required.");
return;
}
else
{ id = encodeURIComponent(id); }
//odataSetName is required, i.e. "AccountSet"
if (!odataSetName)
{
alert("odataSetName is required.");
return;
}
else
{ odataSetName = encodeURIComponent(odataSetName); }
//Asynchronous AJAX function to Delete a CRM record using OData
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: clientUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
beforeSend: function (XMLHttpRequest)
{
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
//Specify the HTTP method DELETE to perform a delete operation.
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
},
success: function (data, textStatus, XmlHttpRequest)
{
if (successCallback)
{
successCallback(data.d, textStatus, XmlHttpRequest);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown)
{
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
errorHandler(XmlHttpRequest, textStatus, errorThrown);
}
});
}
/// <summary>
/// A function that will display the error results of an AJAX operation
/// </summary>
function errorHandler(xmlHttpRequest, textStatus, errorThrown)
{
alert("Error : " + textStatus + ": " + xmlHttpRequest.statusText);
}
1) RESTJQueryContactEditor.htm – An HTML file that references all the needed JScript files and displays output to the user.
2) jquery1.9.1.min.js - A popular JScript library that includes capabilities to perform asynchronous data operations using the $.ajax object
3) RESTJQueryContactEditor.js – A generic library that can perform Create, Retrieve, Update and Delete operations using jquery1.9.1.min.js. This file was created for this example and includes IntelliSense for Visual Studio.
Step8: Open the Configuration
Testing:
No comments:
Post a Comment