Passing japanese parameters in JSONP requests - jsonp

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.

Related

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'.

OpenID Connect Persist ID Token to Server-side Callback Function

Suppose that I invoke the following HTTP request:
https://accounts.example.com/oauth2/auth?
scope=openid+email&
nonce=53f2495d7b435ac571&
redirect_uri=https%3A%2F%2Foauth2demo.appspot.com%2Foauthcallback&
response_type=id_token+token&
client_id=753560681145-2ik2j3snsvbs80ijdi8.apps.googleusercontent.com
Which yields the following redirect response:
https://oauth2demo.appspot.com/oauthcallback#
access_token=ya29.AHES6ZSzX
token_type=Bearer&
expires_in=3600&
id_token=eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiY...
What is the point of the callback parameter, given that the returned metadata, containing id_token, etc., is positioned after a hash fragment in the URI, and are therefore not persisted as parameters to the callback function? How can a server-side callback receive the various tokens?
The response type that is used here is a so-called "Implicit" response type which is primarily meant for in-browser (e.g. Javascript) clients, in which case the Javascript code that is served on the callback URL can access the parameters in the fragment. Web applications should do either one of:
stick to the code flow which is meant for web application clients
use the Form Post response mode (http://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html) if supported by the OP
serve Javascript on the callback URL that parses out the parameters from the fragment and POSTs them to the server
Bottom line is that if you need the tokens server-side, you should most probably use the code response type.

Dynamics CRM 2011 REST API using jQuery

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

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"},

Cannot load Google Images from its API using jQuery getJSON

My code is below:
$.getJSON('https://ajax.googleapis.com/ajax/services/search/images?q=Google&v=1.0',
function(json) {
alert(json);
})​
You can try this code here: http://jsbin.com/ofaru3/edit
The ajax is error
imagesFailed to load resource
How cna I fix this problem? Thanks!
You need &callback=? on the URL there to trigger JSONP, like this:
$.getJSON('https://ajax.googleapis.com/ajax/services/search/images?q=Google&v=1.0&callback=?',
function(json) {
alert(json);
});
You can test it out here. Without the &callback? it's trying to fetch the data from a remote domain with an XmlHttpRequest (AJAX) and failing/being blocked due to the same origin policy. This is exactly the type of situation JSONP is for.
From the $.getJSON() docs:
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.