Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Create a Record from Javascript using web api query

Posted on by 6,203

Hi All, 

I want to create a new record from the below two query, when i set the lookup value i am facing error, but when i use query with out lookup field it works fine. i have check the schema name, below are two was i have check,i am having system admin rights.

1) 

var entity = {};
entity.name = "test";
entity["new_marketid@odata.bind"] = "/new_markets(xxxxxxxx-EF23-E411-A48E-xxxxxxxxx)";

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    url: Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts",
    data: JSON.stringify(entity),
    beforeSend: function(XMLHttpRequest) {
        XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
        XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
        XMLHttpRequest.setRequestHeader("Accept", "application/json");
    },
    async: true,
    success: function(data, textStatus, xhr) {
        var uri = xhr.getResponseHeader("OData-EntityId");
        var regExp = /\(([^)]+)\)/;
        var matches = regExp.exec(uri);
        var newEntityId = matches[1];
    },
    error: function(xhr, textStatus, errorThrown) {
        Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
    }
});


2)

var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = "xxxxxxxx-EF23-E411-A48E-xxxxxx";
lookupValue[0].name = "A&E";
lookupValue[0].entityType = "new_markets";
var entity = new XrmServiceToolkit.Soap.BusinessEntity("account");
entity.attributes["name"] = "test"; 
entity.attributes["new_marketid"] = lookupValue;
var guid = XrmServiceToolkit.Soap.Create(entity);

Both the code not working when using lookup value.

Any help would be appreciated.

Regards,

Shahbaaz

*This post is locked for comments

  • Suggested answer
    Shahbaaz Ansari Profile Picture
    Shahbaaz Ansari 6,203 on at
    RE: Create a Record from Javascript using web api query

    Hi All,

    For the Custom entity we have to pass "Schema Name" and for the OOB Entity we have to pass name, for example below

    var entity = {};

    //debugger;

    entity.name = "test551";

    entity["primarycontactid@odata.bind"] = "/contacts(xxxx-9EE9-E811-A96C-xxxxx)";//primarycontactid is name that is in small letters

    entity["new_MarketId@odata.bind"] = "/new_markets(xxxxxx-EF23-E411-A48E-xxxxxx)";//We need to pass new_MarketId insted of new_marketid that is Schema Name

    var req = new XMLHttpRequest();

    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/accounts", 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.addEventListener("error",function(event)

    {

    console.log(event);

    },false);

    req.onreadystatechange = function() {

    if (this.readyState === 4) {

    req.onreadystatechange = null;

    if (this.status === 204) {

    var uri = this.getResponseHeader("OData-EntityId");

    var regExp = /\(([^)]+)\)/;

    var matches = regExp.exec(uri);

    var newEntityId = matches[1];

    } else {

    Xrm.Utility.alertDialog(this.statusText);

    }

    }

    };

    req.send(JSON.stringify(entity));

    Thanks,

    Shahbaaz

  • Shahbaaz Ansari Profile Picture
    Shahbaaz Ansari 6,203 on at
    RE: Create a Record from Javascript using web api query

    Error Message : The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource

  • Shahbaaz Ansari Profile Picture
    Shahbaaz Ansari 6,203 on at
    RE: Create a Record from Javascript using web api query

    @Goutam : getting 400 error

  • Verified answer
    Sreevalli Profile Picture
    Sreevalli 3,256 on at
    RE: Create a Record from Javascript using web api query

    Hi Shahbaaz,

    you have to use schema name inplace of field name and entity plural name along with guid id.

    sample codesnip,

    "new_Account@odata.bind": "/accounts(" + selectedInvestor.items[i].id.replace("{", "").replace("}", "") + ")",

  • gdas Profile Picture
    gdas 50,085 on at
    RE: Create a Record from Javascript using web api query

    Hi Shahbaaz,

    Can please share the error message which are you getting.

  • Shahbaaz Ansari Profile Picture
    Shahbaaz Ansari 6,203 on at
    RE: Create a Record from Javascript using web api query

    Used below code also, no luck,

    var entity = {};

    entity.name = "tets";

    entity["new_marketid@odata.bind"] = "/new_markets(xxxxx-EF23-E411-A48E-xxxxx)";

    var stringJSONAcc = JSON.stringify(entity);

    $.ajax({

    type: "POST",

    contentType: "application/json; charset=utf-8",

    datatype: "json",

    url: Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts",

    data: stringJSONAcc,

    beforeSend: function(XMLHttpRequest) {

    XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");

    XMLHttpRequest.setRequestHeader("OData-Version", "4.0");

    XMLHttpRequest.setRequestHeader("Accept", "application/json");

    },

    async: true,

    success: function(data, textStatus, xhr) {

    var uri = xhr.getResponseHeader("OData-EntityId");

    var regExp = /\(([^)]+)\)/;

    var matches = regExp.exec(uri);

    var newEntityId = matches[1];

    },

    error: function(xhr, textStatus, errorThrown) {

    Xrm.Utility.alertDialog(textStatus + " " + errorThrown);

    }

    });

  • Shahbaaz Ansari Profile Picture
    Shahbaaz Ansari 6,203 on at
    RE: Create a Record from Javascript using web api query

    Thanks Goutam for the response, entity name is "new_market" and when i used it in the query i passed it as "new_markets" only, but still no luck with all the request above

  • Shahbaaz Ansari Profile Picture
    Shahbaaz Ansari 6,203 on at
    RE: Create a Record from Javascript using web api query

    Thanks Necdet and Wagh for the reply, still facing same issue.

  • Suggested answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: Create a Record from Javascript using web api query

    You can check here sample code for all type of field  -

    www.inogic.com/.../set-values-of-all-data-types-using-web-api-in-dynamics-crm

  • Suggested answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: Create a Record from Javascript using web api query

    1) Seems your code is correct , only thing make sure you provided correct lookup name  and the entity name with additional "s". If the entity name is "new_markets" then put "new_marketss"

    var entity = {};
    entity.name = "test";
    entity["new_marketid@odata.bind"] = "/new_marketss(xxxxxxxx-EF23-E411-A48E-xxxxxxxxx)";
    
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts",
        data: JSON.stringify(entity),
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
            XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        async: true,
        success: function (data, textStatus, xhr) {
            var uri = xhr.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            var newEntityId = matches[1];
        },
        error: function (xhr, textStatus, errorThrown) {
            Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
        }
    });
    


    2) Try with this - You need to add "Set" after entity name .

    Using SOAP

    ===================

    var lookupValue = new Array();
    lookupValue[0] = new Object();
    lookupValue[0].id = "xxxxxxxx-EF23-E411-A48E-xxxxxx";
    lookupValue[0].name = "A&E";
    lookupValue[0].entityType = "new_marketsSet";
    var entity = new XrmServiceToolkit.Soap.BusinessEntity("account");
    entity.attributes["name"] = "test";
    entity.attributes["new_marketid"] = lookupValue;
    var guid = XrmServiceToolkit.Soap.Create(entity);
    


    Using REST
    =========================== var json = {}; jsonDT.new_marketid = { Id: "xxxxxxxx-EF23-E411-A48E-xxxxxx", LogicalName: "new_marketsSet", Name: "A&E" }; json.name = "test"; XrmServiceToolkit.Rest.Create( jsonCOI, "new_marketsSet", function (result) { }, function (error) { alert("error"); }, false );


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

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,214 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans