Special characters encoding in JSON response - ajax

I need to spend Spanish text in json response. I have tried all the possible ways but the message still shows weird characters on the UI. The message I want to show is,
Número de Seguro Social
But it shows up as,
N�mero de Seguro Social
On the Java side,
//response.setContentType("application/json");
//response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
OutputStream out = null;
out = response.getOutputStream();
out.write(jsonResponse.toString().getBytes());
out.close();
added meta tag in head section.
<meta http-equiv="content-type" content="text/html;charset=utf-8">
I have also set the content type in ajax call
$.ajax({
async: false,
cache: false,
type: get,
contentType: "application/json; charset=utf-8",
url: //url,
data: //data,
dataType: //dataType,
success: //callbackfn,
error: //errorfn
});
Nothing seem to work. Is there anything else I can do to get the special characters work as I intended?

I would test where the error is occurring first by sending the string:
"N\u00famero de Seguro Social"
To the browser that is showing the UTF string, just to make sure that it is capable of understanding and displaying the UTF string you're trying to display.
But the actual problem is probably in:
out.write(jsonResponse.toString().getBytes());
As getBytes will get the bytes for the default charset for the system, which may not be UTF-8. You can check this by calling Charset.defaultCharset();
I'm guessing jsonResponse is your own class for storing the response data and then converting it to JSON at the end. I'd recommend using a library from http://www.json.org/ like the Google JSON library for doing the JSON conversion, as there are lots of little gotchas like this one, that are solved problems, so long as you use a decent library to do the encoding/decoding.

$.ajax({
type: "Get",
url: your url,
data: { inputParam : JSON.stringify(inputParam)},
dataType: "json",
success: //callbackfn,
error: //error
});

Related

Unable to download csv file even though content coming in response header

I have this stupid problem that I am seeing my csv data in the response header but it's not downloading the csv.
On client side, I have a button and on it's click an ajax post request is fired like
$.ajax({
url: 'xyz/GenerateCSV',
type: 'POST',
data: postData,
contentType: "application/json; charset=utf-8"
});
On the server side I have set Response as
Response.AddHeader("content-disposition", "attachment;filename=ListExport.csv");
Response.ContentType = "text/csv";
The http response header is coming fine as -
Cache-Control:private
content-disposition:attachment;filename=EncounterListExport.csv
Content-Encoding:gzip
Content-Type:text/csv; charset=utf-8
Date:Mon, 22 Sep 2014 14:18:05 GMT
Server:Microsoft-IIS/8.0
Transfer-Encoding:chunked
Vary:Accept-Encoding
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:4.0
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?
Any idea what's going on? I did not make use of any Form or 'submit' button.
Thanks,
Vaibhav
Regarding your comment above:
It fails in the sense that nothing happens.
That's kind of incorrect. By your own admission, "Response content has data." Therefore something does happen. The response sends the data to the client.
The question is, what do you do with that data? According to your code, nothing:
$.ajax({
url: 'xyz/GenerateCSV',
type: 'POST',
data: postData,
contentType: "application/json; charset=utf-8"
});
Look at the documentation for $.ajax(). You need to provide it with some code to invoke after the response is received. That code would handle the response in some way. Something like this:
$.ajax({
url: 'xyz/GenerateCSV',
type: 'POST',
data: postData,
contentType: "application/json; charset=utf-8"
}).done(function (response) {
// use the data from the response
}).fail(function (response) {
// handle an error from the response
});
What you do with that data is up to you. It's structured CSV data, I imagine there exists some JavaScript library out there which can parse that easily. If you want to save the data to a file then you're going to have to prompt the user in some way (which could involve some trickery and workarounds) or save it to local storage. JavaScript can't write directly to the file system (for obvious security reasons).

Difference betweene datatype XML and HTML

What is the difference between
$.ajax({
type: "GET",
url: "logs/old-vs-new.xml",
dataType: "xml",
success: function(xml) { ...
And
$.ajax({
type: "GET",
url: "logs/old-vs-new.xml",
dataType: "html",
success: function(xml) { ...
I know the dataType is different. But when I use datatype xml I get the parsererror and with datatype html it works fine. It's strange because my file I want to work with is a XML file.
My XML file consist now out of more than 5000 lines, but when a decrement it to about 800 lines it works too with datatype XML.
Someone an idea?
My problem is solved.
My markup wasn't right.
I used special chars between my tags and that was my fault. Now i edited my code and replaced the special chars with html entities.
So peoples with the same problem as me, first try to validate your xml code with a validator which you can find on the web.
Thanks Tony Hopkinson and florin.prisecariu!

Malformed JSON response being sent by Play Server

I am using jquery Ajax to send data to the client and get reply from the Client.
I am using Play Framework as backend.
AJAX:
$.ajax({
type: "GET",
url: '/authenticate',
data: {'type':type, 'redirectURL':getRedirectURL},
contentType: "application/json; charset=UTF-8",
dataType: 'json'
}).success(function( msg, txtStatus, jqXHR) {
console.log("asdasd5= "+msg);
console.log("asdasd5= "+msg.authUrl);
console.log("asdasd5= "+jqXHR.authUrl);
window.location = msg;
});
SERVER DATA CREATION:
response.setContentTypeIfNotSet("text/plain; charset=UTF-8");
Logger.info("response content type ="+response.contentType);
renderJSON("{\"authUrl\": " + authUrl +"}");
The server is sending something like "www.mywebsite.com/yoohoo/auth/1231"
But the response received by Ajax is �����������������{"authUrl": www.mywebsite.com/yoohoo/auth/1231}
DUE to these weird character the JSON response received cannot be parsed by jQuery.
Kindly, help on this.
Thanks
I noted that you are sending back (server-side) a MIME type of "text/plain". Perhaps switch to "application/json". Additionally, you could take the return string and strip any junk from the string before parsing the JSON out on the client side. This would help sanitize in case you change something again server-side and accidentally introduce new/different "junk".

$(document).ready doesn't work however page is loaded

As you can understand my title, browser doesn't call the GetReleatedProducts method. I put breakpoint $(document).ready(function () line but it doesn't enter into ajax call.
I checked that I have jquery reference. Do you have any idea?
$(document).ready(function () {
$.ajax({
type: "POST",
url: "http://localhost:2782/AjaxCallPage.aspx/GetReleatedProducts",
data: "{productId:" + productId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {...}
You've told the server you're sending it JSON:
contentType: "application/json; charset=utf-8",
...but what you're sending it:
data: "{productId:" + productId + "}",
...is not valid JSON. To be valid JSON, the key productId must be in double quotes:
data: '{"productId":' + productId + '}',
// ^ ^
(Here I'm assuming productId is a number. If it's a string, it will also need to be in double quotes.)
So I suspect the server side is rejecting the call because the JSON is invalid.
It's also a bit unusual to send JSON to the server, although it's perfectly valid if that server is coded to expect it and if you send it correctly. It's more typical to send data to the server using the default application/x-www-form-urlencoded.
So unless you've coded your server side to expect to receive JSON, remove the contentType option from your $.ajax call and change data to:
data: {productId: productId}
...which tells jQuery to do the encoding for you.

Need some help combining 2 jQuery scripts and behaviors

Ι need to use a combination of the following 2 scripts but despite all the combinations I've done so far, I fail to get it to work 100%.
I use a colorbox to display products detail pages in which there is a form with various fields for adding the items to the cart. Upon submitting the form, I want to show an alert and then close the colorbox so that the underlying page (that opened the colorbox in the forst place) stays as is.
With this script
$("#productadd").submit(function(){ // WORKS FINE EXCEPT THE ENCODING
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
alert('Product was added to your order');
$().colorbox.close();
});
everything works fine except for the encoding which in my case is iso-8859-7 (greek).
If I use this script then encoding is ok but the post is being made with the default behaviour, redirection to the url defined in the form's action.
$("#productadd").submit(function(){ //ENCODING OK, COLORBOX.CLOSE() AND ALERT FAIL
$.ajax({
data: data,
type: "POST",
url: $(this).attr('action'),
dataType: 'json',
beforeSend : function(xhr) {
xhr.setRequestHeader('Accept', "text/html; charset=iso-8859-7");
},
success: function(json) {
alert('Product added to cart!'),
$().colorbox.close(),
itemAddCallback(json);
},
error: function (xhr, textStatus, errorThrown) {
$("#error").html(xhr.responseText);
}
});
If there's a jQuery equivalent for xhr.setRequestHeader('Accept', "text/html; charset=iso-8859-7") I'd be more than happy to use it. Also, what do I declare as data: so I dont get a 'data is not defined' error? (despite the error, date submits fine).
UPDATE: After various suggestions from those who answered so far, this is what my code looks like:
$("#productadd").submit(function(){
$.ajax({
data: $(this).serialize(),
type: "POST",
url: $(this).attr('action'),
dataType: 'text',
mimeType: "text/html; iso-8859-7",
success: function() {
alert('Item added to your order'),
$().colorbox.close();
},
error: function (xhr, textStatus, errorThrown) {
$("#error").html(xhr.responseText);
}
});
My only problem is that although it submits and displays the alert etc, the submitted data is encoded in utf-8 instead of iso-8859-7, any ideas?
Please check the documentation:
http://api.jquery.com/jQuery.ajax/
Find mimeType property.
mimeType(added 1.5.1)String
A mime type to override the XHR mime type.
Therefore you need to add following:
$.ajax({
data: data,
type: "POST",
mimeType: "text/html; charset=iso-8859-7"...
In the shorthand POST request you send $(this).serialize() as data, so I suppose you want to send the same form data in the other request.
To debug the requests, use your browsers net panel and find out if the requests actually fire and what the responses are (F12 then Net > XHR).
Hope this helps!

Resources