CRM 2011 json data.d.results undefined but URL shows data - ajax

I'm trying to do a simple odata query and the call is successful, but the results are always undefined. I've thrown the URL into the description, copy and pasted it, and it works just fine. I've tested dozens of different ways to see what the object is, and the results are undefined. What am I missing??
UPDATE: As mentioned below, part of the problem was referencing data.d.results. When I referenced data.d.results[0], I actually got the error message "Unable to get property '0' of undefined or null reference." I wanted to add that here because I found almost NO help when searching for that error message.
The final answer was a combination of:
data.d for only one result
correct casing for system fields; "resProd.Description" as opposed to "resProd.description."
Back to orig Question:
Below is the code I'm using:
function setOPDefaults() {
// Create lookup
var lookupItem = new Array();
lookupItem = Xrm.Page.getAttribute("productid").getValue();
if (lookupItem != null)
{
var guid = lookupItem[0].id;
}
var crmOrg = window.location.pathname.split('/')[1];
var serverUrl = window.location.protocol + "//" + window.location.host + (crmOrg == 'userdefined' ? '' : '/' + crmOrg);
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var ODATA_PREP = serverUrl + ODATA_ENDPOINT;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
// Tried both of the following URLS (obviously not at the same time)
url: ODATA_PREP + "/ProductSet(guid'" + guid + "')",
url: "http://crm/<<orgname>>/XRMServices/2011/OrganizationData.svc/ProductSet(guid'67BA90A3-39D8-E211-8D1E-0050569A6113')",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
var resProd = data.d.results;
alert(resProd.length); // This is undefined
// Below is where I load the URL into description just for testing.
// When I copy and paste this URL into the browser, it pulls up results with correct data
Xrm.Page.getAttribute("description").setValue(ODATA_PREP + "/ProductSet(guid'" + guid + "')");
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Ajax call failed: " + textStatus + " - " + errorThrown + " || " + XmlHttpRequest.responseText);
}
});
}

You're acessing just one record, so try put something like that:
data.d
data.d.results is used for multiple results. Another thing you can do to validate the results is put your url directly in browser.

In such cases, I use Fiddler. You can use it to debug your http/https trafic.
Or. If you have crm 2011 RU 12, you can use built-in Chrome debugger. Press F12. In console tab - right click -> Log XMLHttpRequest

Related

Not found error for ajax in ASP.NET MVC release configuration

I am currently working on an ASP.NET MVC site and I am having trouble with ajax posts in my release build. The site has two database connections, one to a "dummy" server that allows me to test code without affecting the live server. So, I had to configure the site to point to the live server for the release configuration, and the dummy server for the debug configuration.
Everything other than the database connection is the same, but for some reason my ajax call works fine on the debug build but throws an error on the release build. I get an ERROR THROWN: Not found alert on the ajax failure, but it only fails in the release build.
My call to the controller method looks like this:
$.ajax({
type: "GET",
url: "#Url.Action("ReleasePlotFieldName", "TestRecord")" + '?fieldName=' + x + '&fileName=' + filename,
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
success: function (data) {
alert("success");
for (var key in data) {
let b = {
name: data[key][0],
value: data[key][1],
line: data[key][2],
arc: data[key][3]
};
chartData.push(b);
}
PlotData();
//the parameter data contains the array returned from the json PlotFieldName function
},
error: function (xhr, textStatus, errorThrown) {
alert('STATUS: ' + textStatus + '\nERROR THROWN: ' + errorThrown);
}
and the controller method looks like this:
[HttpPost]
public JsonResult ReleasePlotFieldName(string fieldName, string fileName)
{
var spiData = (DataDecoder)Session["dataDecode"];
var selectedItem = fieldName;
spiData.DecodeData(selectedItem);
List<float[]> toPlot = spiData.returnPlotVector();
return new JsonResult()
{
Data = toPlot,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
MaxJsonLength = int.MaxValue // Use this value to set your maximum size for all of your Requests
};
}
I have absolutely no clue why the release build is not executing as expected (as the debug build is doing). I welcome any and all suggestions.
Here is the network tab of the browser when the call is made
Your controller action is decorated with a [HttpPost] attribute but your jquery .ajax() request is a GET. Change one or the other depending on your use case (looks like GET could be more appropriate).

JSONP json callback method not called : parsererror

I have the following ajax function using jsonp:
function PopulateDivisions1()
{
$.support.cors=true;
$.ajax({
type:'GET',
url:'http://IP/Service/api/DivisionSearch/GetAllDivisions?callback=?',
dataType: "jsonp",
//jsonp: false,
jsonpCallback: "myJsonMethod",
success: function(data) {
alert('yes');
$("#divisionSelect").append($('<option></option>').val("-99").html("Select One"));
$.each(data, function(i, item){
$("#divisionSelect").append($('<option></option>').val(item.Name).html(item.Name));
});
},
error: function(xhrequest, ErrorText, thrownError) {
alert("Original: " + thrownError + " : " + ErrorText);
}
});
}
I am getting the following error:
myJsonMethod was not called : parsererror
If I look at Fiddler, I am getting the following data back, I added the callback name to the front, as I saw that suggested, if I take it out it still doesn't work.
"myJsonMethod([{\"Id\":1,\"Description\":\"Executive\",\"Name\":\"Executive \"},{\"Id\":2,\"Description\":\"ASD\",\"Name\":\"Administrative Services Division \"},{\"Id\":3,\"Description\":\"COM\",\"Name\":\"Communications \"},{\"Id\":4,\"Description\":\"CP\",\"Name\":\"Contracts and Procurement \"},{\"Id\":5,\"Description\":\"PMD\",\"Name\":\"Program Management Division \"},{\"Id\":6,\"Description\":\"RED\",\"Name\":\"Research and Evaluation Division \"},{\"Id\":7,\"Description\":\"IT\",\"Name\":\"Information Technology \"}])"
Here is the method in my controller:
public string GetAllDivisions(string callback)
{
var divisions = _DivisionModel.GetAllDivisions();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = serializer.Serialize(divisions);
string result = callback + "(" + json + ");";
return result;
}
I'm not getting to my success call, what am I missing or doing wrong?
You dont have to specify a success callback because the jsonp callback will happen automatically as the server side code will return javascript in case of jsonp.
Refer the below answer for working example.
Using jquery jsonp returns error callback function was not called

JSON returned AJAX post jQuery undefined

I am using jQuery to get a list of Names as JSON string -
`
$.ajax({ type: 'POST', url: "../Names.aspx", dataType: 'json', contentType: "application/json; charset=utf-8", data: "NAME=ALL_PROFILES", success: function (data, textStatus, jqXHR)` {
var html = '';
var obj = jQuery.parseJSON(data);
$.each(obj, function (key, val) {
html += '<option value="' + val + '">' + val + '</option>';
alert("Success" + val);
})
$('#selName').append(html);
$('#selName').selectmenu('refresh');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error ' + jqXHR.val + errorThrown.val + textStatus.val);
}
});
The back end is an asp.net page, and when I debug I get the string as "{"Name":["Maria","John","Raj","Rosh","Tony","Name","test3","test4","test5","test6"]}", which I put in JSONLint and validated. It returns an undefined error in the AJAX request above. If I try with a single string "Name":"John", it works perfectly. The function for adding option is not correct for an array of JSON strings(I will work on it once it enter the success block), but I don't understand why it returns an undefined error when it is returning a valid JSON string. Any help would be appreciated.
If your aspx page returns valid JSON and you are using dataType: 'json', you should not use jQuery.parseJSON() on the returned data, since jQuery already parses the returned JSON string into an object.
If you use "Name":"John" it is not valid JSON, so JQuery enters the error callback.
Put an extra paranthesis around the result and it works.It is strange since JSONLint is not validating it now

Dynamics CRM 2011 form jscript to retrieve lookup data

What are my mistakes, why do I get the "object expected" error, and, eventually, how does one debug jScript ?
I am new to Dynamics CRM and I would like to do a small customisation, which seem to require jScript. The instance (version 2011) is used mostly to manage client support.
There are 2 custom entities with relationships: FundLegalEntity --> SubFund
The Case (Incident) form is linked to the FundLegalEntity and the SubFund.
When user enters a SubFund I would like to have the FundLegalEntity filled automatically (if empty).
My question was: how do I code that ?
With the help of this great tutorial, and the very usefull oData Tool, and great help (below) from user #dub, here is my latest code:
function recalcParent()
{
var lookupValue = Xrm.Page.getAttribute("new_subfundid").getValue();
var subFundId= lookupValue[0].id;
// alert(subFundId);
var request = Xrm.Page.context.getServerUrl() +
"/xrmServices/2011/OrganizationData.svc/new_subfundSet?" +
"$select=new_LegalEntityId&" +
"$filter=new_subfundId eq guid'"+ subFundId+ "'";
// alert(request);
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: request,
async: false,
beforeSend:
function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success:
function (data, textStatus, XmlHttpRequest)
{
var result = data.d.results[0];
alert(result);
var parentFundLookup = [{ entityType : "new_fund", id : result.LegalEntityId, name : result.FundLegalEntity}];
// Set the value of the parent fund lookup
},
error:
function (XmlHttpRequest, textStatus, errorThrown)
{
alert('Failed');
}
});
}
I have no more errors, the first 2 alerts (commente out) are giving me correct results.
THe 3rd alert displays "object Object", and the control I expect to update is not updated.
Any hint please ? I suppose the last problem is in the var parentFundLookup = line...
I am a bit confused by all these different names.
Thanks !
Edit:
It's nearly working now: when I modify the sub-fund in the Incident, the Legal Entity gets updated with the correct legal entity name, but the text box has a strange aspect, and the icon at the left of the text box is strange as well. Here is the latest bit of code:
success:
function (data, textStatus, XmlHttpRequest)
{
var result = data.d.results[0];
//alert(result.new_LegalEntityId.Name);
var parentFundLookup = [{ entityType : "new_LegalEntity", id : result.new_LegalEntityId.Id, name : result.new_LegalEntityId.Name}];
Xrm.Page.getAttribute("new_fundlegalentityid").setValue(parentFundLookup);
},
I suspect that the problem lies in the entityType : "new_LegalEntity", but I don't know what to put in there. Any clue on this ? What does that represent ?
Here is a screenshot of the Legal Entity after the Sub-Fund is updated and the script has run.
You can use the Rest endpoint from your script to retrieve data from the organization service. Here's an example to get you started. You can also look at the SDK documentation there's a lot of useful information there.
var subfundid; // get the id from the lookup
var request =
Xrm.Page.context.getServerUrl() +
"/XRMServices/2011/OrganizationData.svc/new_subfundSet?" +
"$select=ParentId&" +
"$top=1&" +
"$filter=new_subfundId eq guid'"+ subfundid + "'";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: request,
async: false,
beforeSend:
function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success:
function (data, textStatus, XmlHttpRequest)
{
var result = data.d.results[0];
var parentFundLookup = [{ entityType : "new_fund", id : result.ParentId, name : result.FundName}];
// Set the value of the parent fund lookup
},
error:
function (XmlHttpRequest, textStatus, errorThrown)
{
alert('Failed');
}
});
Since this code uses JQuery, you'll need to add the JQuery library as a web resource and include it in your form. See CRM 2011 "$ is undefined"

Is it possible to append request parameters to a HTTP DELETE request in ajax?

I'm trying to submit a simple jQuery ajax call but using the DELETE method instead of GET or POST. The method is queried but the parameters don't seem to be passed up - I can see this when I inspect the request URL in firebug. Here's what the code looks like:
$.ajax({
type:"DELETE",
url:"/api/deleteGame",
dataType:"json",
data: "gameId=" + gameId + "&userId=" + userId,
success:function(json)
{
if(json != null && json.errors == undefined) {
alert("Game successfully deleted");
parent.closeDialog();
parent.refreshCaller();
} else {
showServerErrors(json.errors);
}
},
error:function(xhr, textstatus, errorThrown)
{
alert("An error occured! " + errorThrown + ", " + textstatus)
}
});
Does this look okay? Is it correct to append the parameters to the DELETE request string like you would a GET?
I'm using the latest version of Chrome and FF 5.
Thanks in advance,
Gearoid.
See $.ajax with DELETE loses parameters.

Resources