HTML5/JSON : UTF-8 cant read proper characters from json - ajax

My HTML5 app is using JSON to fetch data.
The json contact characters like: ö
but the output in my browser is like: �
I used the following in HTML5 header:
<meta http-equiv="Content-Type"content="text/html;charset=utf-8">
and used this in the AJAX to read the JSON:
$.ajax({
url: "items.json",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
..........
But its not helping me out. What will be the solution to it?
I even tried "ISO-8859-1" on both places.

Make sure your font family that you are using for your site supports the extended characters you are attempting to print. Then use firebug or something similar to view what character set your backend json service is sending back. It may not be sending it back. Also, check to see if firebug is showing the correct character in the JSON response. It's possible that the problem is even further back than you thought.

Related

Allow my Tumblr blog's content to be accessed by another page

I'm attempting to copy all of the actual content from my Tumblr blog using a script I wrote on a different web page, but I'm having a bit of trouble with gaining access to the content. My ajax call is as follows:
$.ajax({
url: "http://solacingsavant.tumblr.com/",
dataType: 'jsonp',
success: function(data) {
var elements = $("<div>").html(data)[0].getElementsByTagName("ul")[0].getElementsByTagName("li");
for(var i = 0; i < elements.length; i++) {
var theText = elements[i].firstChild.nodeValue;
alert(theText); // Alert if I got something
// This is where I'll strip the data for the items I want
}
}
});
but as it is the console gives me an error of "Resource interpreted as Script but transferred with MIME type text/html" which I looked into here and changed the corresponding meta tag in the HTML of my blog to <meta http-equiv="Content-Type" content="application/javascript; charset=utf-8" /> with no success
I also tried using dataType: 'html' (which makes more sense to me) but I was getting a console error of "Origin is not allowed by Access-Control-Allow-Origin" which I also looked into and added a meta tag to my Tumblr blog with <meta Access-Control-Allow-Origin="*" />, but again didn't succeed
Here is a jsFiddle to work with
Does my approach not work because Tumblr as a whole does not allow changes to Access-Control? If so, how might I work around the issue? If not, what am I doing wrong?
MAJOR EDIT (based on mikedidthis's helpful comments)
It seems that I am not able to do this without a Tubmlr API, so I obtained an API key and now have access to the json results that the API sends out. I am able to get a jsonp object using the API key to in the console. My javascript at the moment:
$.ajax({
url: "http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/info?api_key=APIkeyGoesHeRe",
dataType: 'jsonp',
success: function(results){
console.log(results);
// Get data from posts here
}
});
This SO post was helpful in understanding how I can change data on my Tubmlr page from the source and find out basic information about the site, but not about how to obtain actual data from individual posts. I tried looking through the results object and was unable to find any data related to posts, nor was I able to append the results to the jsfiddle. So my questions now are, "Can I copy data (say the written text in a post) from individual posts using this approach? If so, how? If not, what other approach should I use?"
A really quick answer
The tumblr API documentation really covers using the API well, however, to give you a little start, lets grab all your Text Posts.
First you need to query the API for any of your post that are of the type Text.
The documentation states (http://www.tumblr.com/docs/en/api/v2#posts) that we should use the following url and specifying the type which we you will set to text:
api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts[/type]
And below is an example based on the OP fiddle.
$.ajax({
url: "http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts/text?api_key=XXXXXXX",
dataType: 'jsonp',
success: function(data){
posts = data.response.posts
$.each(posts, function(i) {
console.log( posts[i].title, posts[i].body )
});
}
});
So for each query of the API, we will receive back an object. You will need to filter this object to get the data you want from it.
In context of the post queries, you can get directly at your posts using data.response.posts object.
To find out what data is available for each post type, the documentation has it covered: http://www.tumblr.com/docs/en/api/v2#text-posts
To the content for each of the Text post types, you need to loop through the posts object and then grab the value for the key named title and body.
Example here: http://jsfiddle.net/ZpFwL/
Bonus Time
It is possible to get posts for all types, by dropping the type from the URL:
http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts/?api_key=XXXXXXX"
Remember this is a really, quick example and not for the real world.

Ajax result is getting encoded

I have a page where onload I issue several POST requests simultaneously in order to load widgets on the page. The request looks something like this:
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'html',
data: JSON.stringify({}),
success: function(htmlResult) {
$div.html(htmlResult);
}
})
Most of the time everything loads fine. However, some of the time one of the widgets will get loaded with a replacement character. It's not one specific widget that this happens to, but it could be any one of them at random.
When I inspect the bad HTTP response, I notice that the Vary header has a value of Accept-Encoding and the body is encoded. All the other responses have a value of * for that header, and the body is text/html. I'm not explicitly setting the Vary header value anywhere.
I can't figure out what's causing this random behavior. Any ideas?
FYI, I'm posting to an ASP.NET MVC action, and returning a partial view.
have you tried dataType:'json' instead of 'html'?

jquery AJAX response in plain ASCII

I post a pair of chinese characters to my server:
忠孝
the web server then translates them into pinyin:
Zhōngxiào
I know this works, because I got that by directly hitting my AJAX handler. So, the server is encoding everything correctly. However, when I receive that response via jQuery, I get:
Zhōngxiào
My code:
$.ajax({
type: "POST", url: 'procChineseTrans', data: 'toTrans='+text,contentType: "application/x-www-form-urlencoded; charset=UTF-8",
complete: function(data){
//alert(data.responseText);
$('#street_address').val(data.responseText);
}});
I also set:
header('Content-Type:text/html; charset=UTF-8');
and
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
Is there a reason my response is in plain ASCII?
Edit:
Checking my response header, it says it is in UTF-8. But, it is still displaying ASCII
Aha...I see what your problem is. The text/html header you're sending back is causing jquery to parse the responseText as HTML. When you don't specify the dataType option, jquery makes a best guess as to what type of data you're playing with based on response headers.
Try adding dataType : text to the options in your $.ajax call. If that works, then think about adjusting the response Content-type header.
For further reading, search for "dataType" in the jquery manual page : http://api.jquery.com/jQuery.ajax/
Forced it to into html() which formatted it.

jQuery AJAX JSON dataType Conversion

Hopefully that title isn't too cryptic. What's happening is I have a jQuery AJAX script that I'm trying to use to access an API on a remote server, which returns a JSON response. However, the API returns the JSON as MIME type "text/html" (in the response header) instead of "application/json". It would seem obvious that I simply need to change the returned content type from text to JSON, to make the AJAX call interpret the data correctly.
Unfortunately, this is not the case. I have tried this in a multitude of different ways, all of which fail. The closest I've gotten to getting this API call to work is when the debugger tells me "Resource interpreted as Script but transferred with MIME type text/html". And the AJAX call errors out with my debug message that dumps the jqXHR object in JSON format, which tells me: {"readyState":4,"status":200,"statusText":"parsererror"}
Here is an example of my code (although I have changed the code many various ways, in my attempts at getting it to work, but this version seems to be the closest to correct):
$.ajax({
type: 'GET',
url: 'http://username:api-key#www.kanbanpad.com/api/v1/projects.json',
contentType: 'application/json',
dataType: 'jsonp',
converters: {
'jsonp': jQuery.parseJSON,
},
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log(textStatus+': '+errorThrown);
}
});
If anyone can figure out what I need to do differently to make this work, I will be extremely grateful.
It may also be worth noting that if you copy/paste the API URL into a browser address bar and hit go, it gives the proper JSON response with the proper response header ("application/json")
So unless Kanbanpad updates their API, it cannot be directly accessed with JS. You will have to use PHP (or some other) to handle the requests.
It works just as well, it just requires an extra step is all.
Just for anyone that was looking for a solution.
dataFilter(data, type)Function
A function to be used to handle the raw response data of XMLHttpRequest.
This is a pre-filtering
function to sanitize the response. You should return the sanitized data. The function
accepts two arguments: The raw data returned from the server and the 'dataType' parameter.
I would change the content type in the dataFilter interceptor to json. Bear in mind this affects all ajax calls, so use info from data to decide which ones you want to convert.
Verify that your server is sending a jsonp response. This means the json should be enclosed with a string of your callback.
The callback name is passed in the parameters, and if you're not setting it explicitly, looks something like: jQuery15102810791094068532_1300988427891 (As per http://www.json-p.org/)
On your server, you need to format the response:
jQuery15102810791094068532_1300988427891({...json response ...});
Where you use the callback defined in your GET parameter 'callback'.
You might try setting the type to "json" and see if it works. I've had a number of parsererror's with the jquery's jsonp - you might try http://code.google.com/p/jquery-jsonp until it's a bit smoother.
Try changing your content-type to this
contentType: "application/json; charset=utf-8",

jQuery-Ajax JSON charset conflict

I have two comboboxes "A" & "B". Combo "B" is populated using jQuery Ajax (dataType:json) when a value in Combo "A" is selected (onchange event).
There are cases where part of the data in "B" can be chinese/international, in which case the data appears as "????" in the browser.
Typically the entire setup is like so:
ERP <---> Servlet <---> JSP <---> Browser
ERP is UTF-8 enabled. I can clearly see the data in chinese in the ERP console. I've dumped the resultant data that passes into the servlet in a file just to check if it's proper. It's perfectly encoded. I've set the contentType for JSPs to UTF-8. Everything's in place.
I've added the necessary contentType in Ajax to "application/json;charset=utf-8". Still no dice.
That leaves the browser. I've used every browser there is and the same issue arises. I've noticed that the browser simply isn't able to understand the charset of the chinese data when populated on-the-fly.
What can possibly be going wrong? Due to security reasons I cannot post the code. I'd be grateful for any sort of advice.
Thanks a heap!
~Sabier
If you have set your JSP as UTF-8 and your resulting contentType is set to UTF-8 also, you could try this
1) What about using contentType params when you call the servlet, as shown in https://stackoverflow.com/a/6283111/1078487
$.ajax({
type: "POST",
url: "yourservlet",
dataType: "text",
data: {yourparams},// here we def wich variabe is assiciated
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function(data) {
//population
}
});
2) Even if your ERP is setted as UTF-8, just double check those returning string using a UTF-8 byte conversion and see what happens.
byte[] utf8Bytes = stringToParse.getBytes("UTF8");
String stringToReturn = new String(utf8Bytes, "UTF8");

Resources