web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :

JavaScript Callbacks

camelCaseDave Profile Picture camelCaseDave 5

If you need to access the response from an asynchronous XMLHttpRequest, provide your request with a callback. The code below retrieves a Contact from CRM by its ID. In the success function, a callback is called, passing it the result from the request (which should be the Contact).

function getContact(id, callback) {
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/ContactSet(guid'" + contactId + "')",
        beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
        async: true,
        success: function (data, textStatus, xhr) {
            callback(data.d);
        },
        error: function (xhr, textStatus, errorThrown) {
            console.error(errorThrown);
        }
    });
}

To make use of the result, create a function to call getContact, and evaluate its result:

function sayHelloIfNameIsDave() {
    var contactId = Xrm.Page.getAttribute("customerid").getValue()[0].id;

    getContact(contactId, function(contact) {
        if (contact.Firstname === "Dave")
            alert("Hello");
    });
}

The callback is called once the response is ready. Notice that the callback function is passed anonymously here as the second parameter of the call to getContact. It is advisable to write this anonymous function separately and give it a name.


This was originally posted here.

Comments

*This post is locked for comments