Dynamics CRM 2011 REST API using jQuery - api

I personally don't have any experience with CRM 2011 and only recently found out about the REST oData API so decided to have a crack at it using basic jQuery ajax calls. I created a basic html page and put the following code in there from snippets that I picked up from various Google searches. Seems like a fairly straightforward call:
var serverurl = 'http://[OrganizationUrl]/XRMServices/2011/OrganizationData.svc/[PrivateEntity]?$select=[PrivateEntity_Field1],[PrivateEntity_Field2]';
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader('Accept', 'application/json');
},
url: serverurl,
type: 'GET',
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert('success');
},
error: function (xhr, status, error) {
alert("Error : " + status);
},
});
All this does is go to the error callback and alert "Error: parseerror".
A closer inspection on FireBug yields the following request and response headers:
Despite explicitly specifying json in the header and content it still brings back xml/atom feed and still goes the the error callback instead of the success.
Does this JavaScript have to be executed from within CRM i.e. deployed to CRM first? Or can it work as I've done from an external self contained HTML page? I'm familiar with jQuery but not familiar with CRM or this REST API so a little out of my depth here. Any help is appreciated
UPDATE: I've executed the following code in fiddler and it brings back what I expect from CRM:
GET http://[OrganizationUrl]/XRMServices/2011/OrganizationData.svc/[PrivateEntity]?$select=[PrivateEntity_Field1],[PrivateEntity_Field2] HTTP/1.1
User-Agent: Fiddler
Host: melmd0105:5555
Accept: application/json

CRM 2011 REST endpoint is only available for Web Resources, this means that have to be executed from within CRM. Please refer to this page:
http://msdn.microsoft.com/en-us/library/gg334279.aspx
under Limitations you will find this advice:
Use of the REST endpoint is limited to JScript libraries or
Silverlight web resources.

I'll agree with Guido's answer that Microsoft says it is limited to Jscript or Silverlight, but I will say that LinqPad has figured out a way to authenticate, and you can actually write linq queries to generate your RestURL. This has been the fastest method for me to generate Rest URLs for CRM 2011 (only works with On Prem).
NOTE I have attempted to use Fiddler to determine what they are doing to authenticate, but with no success.
Here is an SO question using LinqPad and CRM:
How to perform an ODATA expand in LinqPad

Related

415 Unsupported Media Type in post request

Does anyone know what could cause ERROR 415 (Unsupported Media Type)? Thank you
createArticleOld : async ({ commit, dispatch }, data) => {
let added = await dispatch('authorizedPostOld',
{ action: 'article',
data,
headers: {
'Content-Type': 'application/json-patch+json',
'Accept': 'application/json-patch+json',
},
}
)
console.log(added)
commit('ADD_ARTICLE', added)
},
Typically, an HTTP response status of 415 is telling you that the format of the data you're sending isn't accepted by the server, as described briefly here:
The origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource.
The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.
So, to solve the problem, you need to find out the format that the server expects to receive data in, and send that. The easiest way will be to check the documentation for (or ask the developer of) the server.
If you check the raw response returned to your browser (or perform the same request via something like cURL or Postman), you might find some clues in there as to the formats that the endpoint accepts, or the specific problem causing the error response.
Of course, this relies on the developer of the server implementing the HTTP statuses correctly, and it's quite possible that they've made an error. As a complete guess, given that you're setting the Accept header, it could be that the server is trying to tell you that it can't give you a response in the format "application/json-patch+json", although that should give you a 406.

How to prevent some methods

I'm developing some APIs with Laravel 5.5
The methods I am using are only 'GET'/'POST'/'PUT'/'PATCH'/'DELETE'.
All works fine except if the request is HEAD or LOCK (for example) ....
In this case, the backend returns a 405 error with an html response. And in this html response there are a lot confidential data.
Is it possible , only for some methods, that the back returns a single text "Method not allowed" and not an html file ? Is it a good practice to do that or not necessary?
I imagine a middleware, but which one?
The reason you're getting debug information with confidential data is likely due to debug being set to true in your config. If you turn this to false, the error message will remove the confidential data.
I found a solution.
File Exceptions/handler.php, method render, I had this:
if ($request->is('api/*') and ! in_array($request->method(), ['get', 'post', 'put', 'delete']) ){
return response()->json("request not allowed", 405);
}
It works fine. Now I receive a JSON response instead of an HTML response for all my API routes, depending on 'get/put/post/delete'.

Passing japanese parameters in JSONP requests

Iam having a spring MVC application hosted in a tomcat server.
I tried to develop a widget which could be embedded in any client application for searching
in the external spring MVC application.
I used JSONP in the client application for communicating with the external application.
but iam not able to pass japanese characters as request parameters as it is into the spring mvc application.
Here is the client side code I used.
$.ajax({
type: "GET",
url : "http://abc.com:8080/myTestapp/search?callback=mycallback",
data: ({name : $('#form-refineSearchQuery').val(),iDisplayStart : 0,iDisplayLength: 100}),
dataType: "jsonp",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
jsonp : false,
});
I have an input text box with id form-refineSearchQuery where I gave a japanese character.
But the request parameter is getting encoded into some other format and is reaching the server as some encoded data eg :æ??å¸?å­?
This is the parameter i gave in the input text box- 有希子
Any help?since this issue is causing the search in the spring application to fail
Hey there user2330825!
The problem comes from how JSONP is implemented--it creates a script tag within the DOM, and submits from there as a GET request, and browsers will typically ignore any encoding specification from that, and rely instead on the response encoding. Try adding a charset attribute to your Content-type header on the response (i.e., in the request handling on the server side, set_header("Content-type", "text/javascript; charset=UTF-8"), and see if that works for you.

Dojo Toolkit JSONP on Youtube

How can I send JSONP request on Youtube video? I trying to get the video JSON info file using this code:
define ["dojo/request/script", "dojo/domReady!"], (script) ->
script.get("//gdata.youtube.com/feeds/api/videos/NKE-RXR_XIs", {
jsonp:"callback",
query: {
v: "2",
alt: "json"
}
}).then (response) ->
console.info response
But I getting error 400 (Bad Request). In Chrome console I can see full error:
GET http://gdata.youtube.com/feeds/api/videos/NKE-RXR_XIs?v=2&alt=json/[?&]callback=/dojo_request_script_callbacks.dojo_request_script0 400 (Bad Request)
Where cen by problem please?
The good news, I don't think you are doing anything wrong. I have a similar problem using the Dojo toolkit v.1.8.3 to make JSON-P calls.
The bad news, I just tracked it down to a bug in: dojo/request/script.js
Dojo is making a bad request because a RegExp object is being appended to the URL query string instead of the callback parameter. You can see it in your error message as: /[?&]callback=/.
That bit should just be: &callback=
Looks like they may get it fixed in v.1.8.4
http://bugs.dojotoolkit.org/ticket/16408

jQuery POST does not send JSON data

I'm trying to do a POST to a service running on localhost with jQuery AJAX, but it keeps returning status code 0 even after I've set jQuery.support.cors = true. I can also navigate to my WCF REST service successfully from my browser. This is what my JavaScript looks like:
<script>
jQuery.support.cors = true;
$(document).ready(function(){
$.ajax({
type: "POST",
url: "http://localhost:8000/Test",
data: '{"test":"test"}',
contentType: "application/json",
dataType: "json",
success: function (msg) {
alert('success');
},
error:function(x,e){
if(x.status==0){
alert('error 0');
}
}
});
});
</script>
Does anyone know what could be causing this? I should also mention that I can't POST to anything on localhost using jQuery.
According to Fiddler, the JSON data is not sent, and a HTTP OPTIONS is done instead of a POST.
try this
var dataObj = {test:"test"};
var json = JSON.stringify(dataObj);
then in your ajax call
data: json,
I didn't want to spend anymore time on this issue, so I resorted to using raw HTML form POST as the usage of JSON wasn't essential in my case.
For anyone else having the same issues outlined in the original post, see this thread for an explanation and a solution: Problem sending JSON data from JQuery to WCF REST method
To summarize, your service needs to be able to handle the HTTP OPTIONS method if it is expected to respond to cross domain calls.
You should use a tool like network monitor etc. to see if the browser is asking the server for the allowed headers (using the OPTIONS header request), you may need to supply the correct headers in an OPTIONS response before the actual request is sent to the server (see the article at the bottom).
Also, you could try adding this to the actual call or the ajaxSetup, as you will need to tell the browser to send credentials and allow the cross domain call (I know someone else already mentioned 'crossDomain'):
$.ajaxSetup({
crossDomain: true,
xhrFields: {
withCredentials: true
}
});
Have a read of this if you get time too.. https://developer.mozilla.org/en/http_access_control
So, when the request is cross domain, jQuery will send your post request as a get request anyways.
Are you accessing "localhost" in the URL but then your application is sending the requests to the local IP of your machine instead of localhost? Because that's technically cross-domain, which means that you won't receive the request in the expected manner.
E.g. (just tested this locally)
Visiting my local site at:
http://localhost/test/
A form on the site submits to my local ip address instead of localhost via $.post():
<form action="http://10.0.0.17/test/" method="post">
....[form stuff...]
</form>
This is a cross-domain request
If you're calling $.post() or jquery's ajax() call set to post, it automatically moves your parameters from the post body into the query string.
If you ARE accessing local host, try hitting the site via whatever address your jquery post() method is using as the domain and see if that helps.
See more on cross-domain policies:
http://en.wikipedia.org/wiki/Same_origin_policy
Send the data as an Object literal instead of a string
data: '{"test":"test"}',
to
data: {test:"test"},