jQuery ajax data.d undefined - javascript

I am trying to get CRM data using the Ajax call. Data is being returned with 'd' and 'result' properties but I can't get it on client side. It says ajaxdata.d is undefined.
A sample Ajax call:
var context = Xrm.Page.context;
var serverUrl = context.getClientUrl();
var ODATA_ENDPOINT = context.prependOrgName("/xRMServices/2011/OrganizationData.svc");
var filter = "?&$select=cc_TypeID,cc_customentityId,cc_anotherAttribute&$filter=cc_TypeID eq '2'";
var odataUri = ODATA_ENDPOINT + "/cc_customentitySet" + filter;
console.log("odataUri: " + odataUri);
//Asynchronous AJAX function to Retrieve a CRM record using OData
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataUri,
async: false,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (ajaxdata, textStatus, XmlHttpRequest) {
//console.log("cc_campaignSynch.htm > ready > $.ajax success: " + data);
debugger;
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
console.log("cc_campaignSynch.htm > ready > $.ajax error: " + XmlHttpRequest.responseText);
}
});
Snapshot of data returned:
Updated Snapshot (JSON.parse used):

Might be something of nothing, but try changing "datatype" to "dataType"

To force jQuery magic work and recognize the data type, try to send the response back with HEADER: "Content-Type: application/json".

Related

Send ajax GET request to ASP .NET Web API

I use the following ajax script.
$.ajax({
dataType: 'json',
url: url,
data: tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
The attribute Route in Web API before method.
[Route("api/tudisp/Edit/{tuDispId}")]
public IHttpActionResult Edit(int tuDispId)
{
}
The genarated request from ajax.
http://localhost:xxxxx/api/tudisp/Edit/?179
How to force ajax to not generate sign '?' by id parameter.
The simplest way to do it is to change the url property of the Ajax options...
$.ajax({
dataType: 'json',
url: "http://localhost:xxxxx/api/tudisp/Edit/" + tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
GET parameters are automatically appended to the Url as a querystring, which is fine if that's what your application is expecting, but not when you're using routing as you are.
However, if you wanted to modify existing Ajax requests you can use prefiltering. This example modifies the Url of the ajax call, replacing {variable} with a given value from the data object...
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
options.data = ""; // this removes the querystring
for (key in originalOptions.data) {
options.url = options.url.replace("{" + key + "}", originalOptions.data[key]);
}
});
$.ajax({
url: "http://localhost:xxxxx/api/tudisp/Edit/{tuDispId}",
data: {
"tuDispId": 179
}
});
If you wanted to use something like that then I'd strongly recommend spending a bit of time making it more robust, but it's an example of how you could do what you want.

How to call an external page using pure JavaScript

I would like to call an external page (which I can control) from another domain (which I cannot control). Below is the script I use to call, but the page is not being called.
$(function () {
var val = window.location.hostname;
alert(val);
$.ajax({
type: "GET",
async: false,
crossDomain: true,
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: "http://somedomain.com/validate.aspx/validfunction",
data: "{domain: '" + val + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
console.log(jqXHR, textStatus, errorThrown);
}
});
});
No idea, why I cannot call. Is there any better way to call the page. Please advice.
Use XMLHttpRequest object to make a request like below
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET",URL,true);
xmlhttp.send();
The request is obviously GET and 'URL' is the url you want to execute/open. The 3rd parameter is for async request, it can be either true or false.
Create a div element for eg: with id - result and append the result received in #result element, you can simply use this in the next line:
document.getElementById("result").innerHTML = xmlhttp.responseText;
contentType is set to "application/json; charset=utf-8" though value of data option, for example
"{domain: '1'}"
is not valid JSON. Property names should be surrounded by double quotes.
Create a javascript plain object, populate with properties, values, then pass javascipt plain object to JSON.stringify(), set data as valid JSON result.
See $.ajax([settings])
contentType (default: 'application/x-www-form-urlencoded;=UTF-8'`)
Type: Boolean or String
When sending data to the server, use this content type. Default is
"application/x-www-form-urlencoded; charset=UTF-8", which is fine for
most cases. If you explicitly pass in a content-type to $.ajax(), then
it is always sent to the server (even if no data is sent). As of
jQuery 1.6 you can pass false to tell jQuery to not set any content
type header. Note: The W3C XMLHttpRequest specification dictates that
the charset is always UTF-8; specifying another charset will not force
the browser to change the encoding. Note: For cross-domain requests,
setting the content type to anything other than
application/x-www-form-urlencoded, multipart/form-data, or text/plain
will trigger the browser to send a preflight OPTIONS request to the
server
$(function () {
var val = window.location.hostname;
alert(val);
var data = JSON.stringify({"domain": val});
$.ajax({
type: "GET",
async: false,
crossDomain: true,
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: "http://somedomain.com/validate.aspx/validfunction",
data: data,
success: function (data) {
alert(data.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
console.log(jqXHR, textStatus, errorThrown);
}
});
});
You can alternatively try to use $.getJSON() both with and without "?callback=?" appended to URL.
JSONP
If the URL includes the string "callback=?" (or similar, as defined by
the server-side API), the request is treated as JSONP instead. See the
discussion of the jsonp data type in $.ajax() for more details.
var val = window.location.hostname;
var data = JSON.stringify({"domain": val});
$.getJSON("http://somedomain.com/validate.aspx/validfunction?callback=?", data)
.then(function(data) {
// do stuff with `data`
})
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
});
Whenever we request web-method from ajax method, it should be type 'POST' and for cross domain the datatype is 'JSONP'. The web method should return data as in JSON format.
$.ajax({
type: "POST",
async: false,
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
url: "http://somedomain.com/validate.aspx/validfunction",
data: "{domain: '" + val + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
console.log(jqXHR, textStatus, errorThrown);
}
});

How to parse response as json object for cross domain ajax call?

I'm making a cross domain ajax call. When I heat the link directly from my browser, I get the json strin as follows:
But when I'm making an ajax call to this same URL, I'm not getting the json in my response. My ajax request is as follows:
$.ajax({
url: "http://172.16.201.14:801/api/apiclearing?trackNo=" + $scope.BillClearingModel.BillTrackingNo + "&&tokenNo=~Ice321",
dataType: 'jsonp',
success: function(response) {
console.log(response);
alert("Success");
},
error: function(response) {
console.log(response);
alert("Failed");
}
});
What Im getting in console is as follows:
Full Object is as follows:
What I'm missing here? Thanks.
Would you mind trying this:
var datastring = { "trackNo" : "160822000037" };//try this
//var datastring = "trackNo=160822000037"; //or this
$.ajax({
type: 'POST',//you may try the GET type
url: "https://172.16.201.14:801/api/apiclearing",
dataType: 'json',// try jsonp as well
data: datastring,
contentType: 'application/json',
crossDomain: true, //newly added
success: function(data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(JSON.stringify(data));//to string
alert("Success");
},
error:function(jqXHR, textStatus, errorThrown) {
alert("Status:"+ textStatus + " Error:" + errorThrown);
}
You may consider as well to add Access-Control-Allow-Origin to your server like Access-Control-Allow-Origin: http://yourdomain-you-are-connecting-from.com in php

How to parse parameters from Ajax return string

I have a litte problem.
I call an file and this file has to know from which level it was called.
I'm developing in an special tool, and thats how it works here.
for example:
var Url = baseUrl + "?func=ll&objId=" + WebreportId + "&objAction=RunReport";
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
success: function(response){
$('#thirdPartyContent').html($(response).find('#cvDossier').html());
}
});
In my JavaScript Functions in the Call, i have to know from which level it was called. Like here "dossier".
How can i read out an string in the call? With the URL Parms i can just check the superior url, and not the url from the ajax call, isn't it?
I hope you understand my probs.
Try utilizing beforeSend option of $.ajax()
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
beforeSend: function(jqxhr, settings) {
// set `data` property at `jqxhr` object
jqxhr.data = settings.url..match(/=.*/)[0].split(/=|&.*/).filter(Boolean)[0];
},
success: function(response, textStatus, jqxhr){
// do stuff with `jqxhr.data` : `"dossier"`
console.log(jqxhr.data);
$('#thirdPartyContent')
.html($(response).find('#cvDossier').html());
}
});

Retrieving data using ODATA with javascript

I'm trying to return a result set from crm using odata. i'm new to this.. i want to have an asp.net page displaying the values in a datagrid. i'm getting the error odata execution error popup. if i put in the correct server and query string it always fails though.. any suggestions on how to get this work properly
function ExecuteQuery(ODataQuery) {
//var serverUrl = Xrm.Page.context.getServerUrl();
var serverUrl = "https://server.server.com"; //would be the real server
// Adjust URL for differences between on premise and online
// if (serverUrl.match(/\/$/)) {
// serverUrl = serverUrl.substring(0, serverUrl.length - 1);
// }
alert("test");
var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataURL,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
//
// Handle result from successful execution
alert("success");
//data.d.results
},
error: function (XmlHttpRequest, textStatus, errorObject) {
//
// Handle result from unsuccessful execution
//
alert("OData Execution Error Occurred");
}
});
}
<script type="text/javascript">
ExecuteQuery("the query would go in here);
</script>

Categories