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>
Related
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.
I want to know how can I send the image data to the server (Django app) using javascript ajax function.
Following is my code.
// Get filename of image
jsondata = JSON.parse(data);
image_file_name = jsondata.fileurl;
// document.getElementById('previewimage').src = image_file;
// I can show the image.
b64_image = btoa(unescape(encodeURIComponent(image_file)));
var credentials = {
filename: image_file_name,
image: b64_image,
};
// Send ajax request to the server
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'GET',
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
// Get the result
jsondata = JSON.parse(data);
alert("File upload completed...");
})
// If false...
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Upload error");
})
You have to use FromData for posting files using ajax .
var form = $('form')[0];
var formData = new FormData(form);
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
// success code .
}
});
You just need to make one change in your code.
// Send ajax request to the server
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'POST', // changed from GET to POST
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
// Get the result
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Upload error");
})
as GET is use to read and post is used to create.
you can read more about request methods.
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".
I'd like to know if there is a better approach to creating re-usable ajax object for jquery.
This is my un-tested code.
var sender = {
function ajax(url, type, dataType, callback) {
$.ajax({
url: url,
type: type,
dataType: dataType,
beforeSend: function() {
onStartAjax();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
callback.failure(XMLHttpRequest, textStatus, errorThrown);
},
success: function(data, textStatus) {
callback.success(data, textStatus);
},
complete: function (XMLHttpRequest, textStatus) {
onEndAjax();
}
});
},
function onStartAjax() {
// show loader
},
function onEndAjax() {
// hide loader
}
};
<script type="text/javascript">
var callback = {
success: function(data, textStatus) {
$('#content').html(data);
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error making AJAX call: ' + XMLHttpRequest.statusText + ' (' + XMLHttpRequest.status + ')');
}
}
sender.ajax(url, type, dataType, callback);
</script>
You can set the basic options that you always have the same separately.
for instance if you always use the same thing here:
type: type,
dataType: dataType,
for those types, you can set them separately.
Here is how you do that type of thing:
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}"
});
NOW those are set and you can simplify your individual ajax calls.
EDIT:
NOTE: Setting parameters to $.ajax override these defaults. Thus presetting “data” to an empty JSON string is safe and desired. This way, any $.ajax call that does specify a data parameter will function as expected, since the default will not be used. This helps avoid issues that can be difficult to find on a deployed site.
Here is what I did:
var ajaxclient = (function (window) {
function _do(type, url)
{
return $.ajax({
url:url,
type:type,
dataType:'json',
beforeSend: _onStartAjax
}).always(_onEndAjax);
}
function _onStartAjax()
{
console.log("starting ajax call");
}
function _onEndAjax()
{
console.log("finished ajax call");
}
return {
do:_do
}
}(this));
Example usage:
ajaxclient.do("get","http://...").done(function(data) {console.log(data);})
I'd probably go the whole hog and have an Ajax Object create.
var ajax = new MySuperAjax(url, data);
ajax.onComplete = function(){}
or similar. You seem to have a halfway between a function which has some defaults it extends with those you apss in and an object for it.
can somebody please tell me, how can I display json data returning from the ajax call. I am new to this.
$.ajaxSetup({
cache: false,
timeout: 5000
});
//String.prototype.toJSON;
var the_object = {};
function concatObject(obj) {
strArray = []; //new Array
for (prop in obj) {
strArray.push(prop + " value :" + obj[prop]);
}
return strArray.join();
}
//var ntid = "hhsh";
//document.writeln("httpRequest.responseText");
$(document).ready(function() {
$("button").ajaxStart(function() {
alert('Triggered ajaxStart handler.');
});
$("button").click(function() {
$.ajax({
type: "POST",
dataType: 'JSON',
//data: "{'ntid':'john'}",
//contentType: "application/json; charset=utf-8",
//processData: false,
url: "Testing.aspx/SendMessage",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function(result, txtStatus, httpRequest) {
alert(txtStatus);
//$('#status').html(httpRequest.responseText);
//the_object = result;
$('#status').html(concatObject(result));
//$('#status').html(the_object);
//alert("hello" + concatObject(the_object));
//document.writeln(concatObject(the_object));
}
});
//alert(concatObject(the_object));
//$('#status').html(concatObject(the_object));
});
});
above is the js file. should i need to do something on asp file directly to display it. if yes, then how? please reply me soon. i m stuck here and unable to display data here. Its only diplaying this line:
toJSON value :function (key) { return this.valueOf(); }
Your result is most likely rooted with a property named d. Try modifying your success to use result.d;
This is usually a security measure that has to do with exploits which target a JSON collection with single root parent.