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 :
Customer experience | Sales, Customer Insights,...
Suggested answer

Javascript Call to API

(0) ShareShare
ReportReport
Posted on by 694

Good afternoon everyone,

I am creating an integration in my company and I would like to see if it is possible to do it in the following way

Within the Lead I have a field that is the Client ID, when the user enters this ID, I wanted to see if there is a javascript that makes a call to an API of mine that queries for this ID, if it exists it should return the values as Name and other information for the user, otherwise he displays an alert,

Is there any javascript that runs this way?

Thanks

I have the same question (0)
  • Suggested answer
    Wahaj Rashid Profile Picture
    11,321 on at
    RE: Javascript Call to API

    Hi,

    Thank you for your query.

    You can register an on-change event (JS function) on the Client ID Field, and then call our API.

    Adding a JavaScript Function to a Field in Dynamics 365 Power Apps On Load with addOnChange - Carl de Souza

    Or you can, follow these steps:

    • Go to Advanced Settings -> Customization -> Customize this system.
    • Expand Entities -> <Entity Name> -> Forms.
    • Open the form you need to implement logic on.
    • Click on Form Properties.
    • In the Event tab, click Add in Form Libraries section.
    • Click on New (or use existing JavaScript Web Resource).
    • Create a Java Script Web Resource and add following sample code:

    // On change of Client ID
    function clientIDOnChange(executionContext) {
    
        const clientIdAttribute = executionContext.getEventSource();
    
        const clientIdValue = clientIdAttribute.getValue();
    
        console.log(clientIdValue);
        
        // Implement your logic here
    
    }

    • Save and Publish the web resource.
    • Use this Web Resource on the Form (add as Library).
    • Now, double click on the Client ID field to open properties.
    • On the event tab, click on Add under Event Handlers.
    • Select the Form Library (Web Resource) and enter function name (for this example clientIDOnChange).
    • Check Pass execution context as first parameter, and then click OK.
    • Save and Publish the form.

    Now when you change Client ID value, it should log in the console.

    You can call your API in the same function, here is sample code:

    Call External Api from Javascript - Dynamics 365 General Forum Community Forum (dynamics-int.com)

    If you CORS issue, refer to below:

    Arpit's Dynamics 365 Blog: Call External Web Service using Custom Action in CRM 2013/15 (arpitmscrmhunt.blogspot.com)

  • Ricardo Rodrigues dos Santos Profile Picture
    694 on at
    RE: Javascript Call to API

    Hola Wahaj Rashid,

    Thanks for the answer, a question, the values that the API returns to me can I get them and fill in the fields of the MSCRM form?

    Thanks

  • Suggested answer
    Fubar Profile Picture
    2,756 on at
    RE: Javascript Call to API

    Yes, similar to the code block provided by in the earlier post use setValue('myvalue') instead of getValue()

    docs.microsoft.com/.../setvalue

  • Ricardo Rodrigues dos Santos Profile Picture
    694 on at
    RE: Javascript Call to API

    Good morning,

    I'll try to explain better, I have field A that when it is changed, it will take its value, plus the value of field B and pass it by parameter to the method below, but I couldn't find anything that does this via Javascript, or be it calling a URL from another API passed the value of these two fields as parameter, the method is below, if anyone can help me please remembering that it will return a JSON and I need to get this data to give an alert to the user.

    pastedimage1626706787285v1.png

    Thanks

  • Suggested answer
    Sergi Valero Profile Picture
    145 on at
    RE: Javascript Call to API

    Hello Ricardo Rodrigues dos Santos!

    I am going to write an example function that you will be able to use:

    function ExampleFunction (context) {
        const formContext = context.getFormContext();
        const fieldA = formContext.getAttribute('fieldA').getValue();
        const fieldB = formContext.getAttribute('fieldB').getValue();
        
        const result = fieldA   fieldB;
        
        // Change ... with your API call using
        const requestResult = ...;
        
        if (requestResult === null || requestResult === '') {
            alert('Client Does not Exist');
        } else {
            const clientObject = JSON.parse(requestResult);
            // Once the JSON string is deserialized, you can set the values of the form
            // Note this is an example, I dont know the sctructure of the Client Object
            
            formContext.getAttribute('name').setValue(clientObject.name);
            formContext.getAttribute('otherField').setValue(clientObject.otherFieldData);
            // ....
        }
    }

    If you need a more detailed function, let me know and we can take a look

  • Ricardo Rodrigues dos Santos Profile Picture
    694 on at
    RE: Javascript Call to API

    Hello Sergi, good morning,

    Thanks for the answer, but I ended up with some questions that are:

    Inside the Lead I have a key field which is the cnpj, I also have a key of my Seller which is the CPF.

    When he types the CNPJ, he records this information and the CPF in variables and passes them as a parameter to the API.

    If you have found it has the parameter "ClientAuthorizado" which returns true, then I will display an alert to the user stating that this Lead already belongs to another Seller, otherwise I will not inform anything and he can follow the registration.

    My doubt is that in the example call you gave me, I didn't see where I compare the API return with the two variables to find out if it found it and another point is that I'm passing in an if the parameter AuthorizedClient as true, because the JSON returns true, if that's right, below the code example.

    function ExampleFunction(context)
    {
    const formContext = context.getFormContext();

    const cnpj = formContext.getAttribute("new_cnpj").getValue();
    const ownerid = formContext.getAttribute("ownerid").getValue()[0].id;
    alert(ownerid)
    //const result = fieldA + fieldB;

    if(cnpj != null && ownerid != null)
    {
    // Change ... with your API call using
    const requestResult = "/api/vi/persons/getClient";

    if (requestResult === null || requestResult === "")
    {
    alert('Client Does not Exist');
    }
    else
    {
    const clientObject = JSON.parse(requestResult);
    // Once the JSON string is deserialized, you can set the values of the form
    // Note this is an example, I dont know the sctructure of the Client Object

    if(clientObject.ClientAutorizado == true)
    {

    /*formContext.getAttribute('name').setValue(clientObject.name);
    formContext.getAttribute('otherField').setValue(clientObject.otherFieldData);*/
    }
    }
    }
    }

  • Sergi Valero Profile Picture
    145 on at
    RE: Javascript Call to API

    Hey Ricardo!

    Could you please provide more information? It will be easier and faster to find a solution to your problem. Because my approach was assuming you didn't need to compare the information you got from the API call and the fields in CRM because you used them to make the query in the first place.

    1. What does the API return in both success and failure cases? Is it a boolean? Is it an object?

    2. What do you want to do with the response? Do you just need an alert in case the client already exists? Or you want to populate some fields with the information you got from the API?

  • Ricardo Rodrigues dos Santos Profile Picture
    694 on at
    RE: Javascript Call to API

    Hey Ricardo!

    Could you please provide more information? It will be easier and faster to find a solution to your problem. Because my approach was assuming you didn't need to compare the information you got from the API call and the fields in CRM because you used them to make the query in the first place.
    And yes I get fields from CRM. In case I have a code inside the form, when changing this field I need to go to the user table and get another code.

    This code returns me from the user table and the user ID in the company so I compare this value passing it as a parameter in the API call, the problem is that I'm already getting a direct error, it doesn't even call the method.


    1. What does the API return in both success and failure cases? Is it a boolean? Is it an object?
    Hello the API of the direct error stating that the method does not exist but exists

    2. What do you want to do with the response? Do you just need an alert in case the client already exists? Or do you want to populate some fields with the information you got from the API?

    If the answer is yes, I will clear the code field to prevent him from registering the record because he is with someone, otherwise I give an alert and he can register

    Below is an example of my code and the error I'm getting from the copier even though the function is set within the field's properties.

    function Valida(context)
    {
    debugger;

    var formContext = context.getFormContext();
    var OnwerID = formContext.getAttribute("onwerid").getValue()[0].id;
    var codigo = formContext.getAttribute("codigo").getValue();

    Xrm.WebApi.online.retrieveMultipleRecords("systemuser", "?$select=id&$filter=systemuserid eq " + OnwerID + "").then(
    function success(results)
    {
    for (var i = 0; i < results.entities.length; i++)
    {
    var id = results.entities[i]["id"];
    }
    alert(id);

    $.ajax({
    url: "">api/.../GetPersons + codigo + "&command.id="+ id";
    type: "GET",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    async: false,
    crossDomain: true,
    success: function(data, textStatus, xhr) {
    alert("A");
    var result = data;
    alaert(result);
    },
    error: function(xhr, textStatus, errorThrown) {
    Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
    }
    });

    },
    function(error) {
    Xrm.Utility.alertDialog(error.message);
    }
    );
    }

    pastedimage1628712534854v1.png

    pastedimage1628712613885v2.png

    Can someone help me?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Rishabh Kanaskar Profile Picture

Rishabh Kanaskar 228

#2
Tom_Gioielli Profile Picture

Tom_Gioielli 156 Super User 2025 Season 2

#3
MVP-Daniyal Khaleel Profile Picture

MVP-Daniyal Khaleel 149

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans