Ajax, Request Header UTF-8 to ISO Charset [duplicate] - php

This question already has answers here:
Cannot set content-type to 'application/json' in jQuery.ajax
(11 answers)
Closed 7 years ago.
I have a page which is encoded iso-8959-9. Im sending ajax requests to same page while saving some data to DB. But its converts the chars to utf-8.
My response header seems good with charset iso-8859-9. But the Request Header, Content-Type data always UTF-8. please refer to screenshot below.
Here is what ive done to solve this:
1- I set php header iso-8859-9
2- I changed apache's default charset to iso.
3- i set ajax options beforeSend, setRequestHeader and contentType as iso.
4- i modified jquery.js and set ajax default encoding as iso.
none of them didnt solve my problem. i dont want to do any php charset encoding btw.
Any other ideas ?
Thanks
my ajax code:
`
$.ajax({
url: window.location.href,
type: 'POST',
data: $(this).serialize(),
contentType: "application/x-www-form-urlencoded; charset=iso-8859-9",
success: function(result) {
$('#IcerikContent').html($(result).find("#Icerik"));
$('html, body').animate({scrollTop: 0}, 500);
Metronic.initAjax();
if (typeof initialize == 'function') { initialize(); }
stopPageLoading();
}
});
`

I'm afraid that AJAX POST requests must use UTF-8. The jQuery manual explains it:
POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.
You might now wonder about the contentType setting:
Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.
In other words, you have no choice. You either need to migrate your server-side code to UTF-8, make an explicit conversion —iconv() and mb_convert_encoding() will come in handy— or figure out a witty JavaScript trick (such as serialising data before submission).

Related

Getting UTF-8 polish characters after serialization data using Jquery

I wrote script that are sending data from HTML form to server using ajax request.
$.ajax({
type: $(this).attr('method'),
cache: false,
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json'
});
I input data into my HTML form with:
name = 'ładna pogoda'
My $_POST data in PHP script looks like: Array ( [name] => Ĺadna pogoda )
Data stored in MySQL: ?adna pogoda
It's possible to convert data to get utf-8 characters in my php script after serialize() data in javascript?
UPDATE:
My MySQL table was encoded with utf8-general-ci but somehow my columns where I stored data was latin1. When I changed it to table default it starts working.
Make sure that your HTML file is encoded in UTF-8 and that you declared proper charset in its head - in HTML5: <meta charset="UTF-8">. Making sure that your php files are also encoded in UTF-8 can be the next step if the first one does not resolve the issue.

Getting wrong charset output from AJAX

When I want to printout the output of jQuery AJAX, which has been recived from server. It doesn't show the right charset. What I want exactly is to get Š instead I am getting ?. All files script.js and server php proceed.php are saved in UTF-8 and set in UTF-8. Database is set to UTF-8 as well. I've tried most of the things.
In .js file for AJAX:
$.ajaxSetup({
url: "proceed.php", //file to procces data
ContentType : 'charset=UTF-8', // tried here
global: false,
type: "POST",
dataType: "html"
});
In .php file:
mysql_query("SET NAMES utf8");
$output = utf8_decode($sql_result);
All possible combinations.
UPDATE:
I've tried all proposed method in all possible variations and by using them, I don't get any response from server. The only time I get at least soem response is with settings mentioned above - literally. Setting AJAX dataType: "text/html" nor dataType: "application/html" doesn't help.
CODE:
PHP
if(!empty($_POST['select_had'])){
$zem = $_POST['select_had'];
$vysledek = mysql_query("SELECT typ_hadanky, jazyk FROM hlavolam RIGHT JOIN hadanka ON hlavolam.id_hlavolamu=hadanka.id_hlavolamu WHERE zeme_puvodu='$zem'");
$out = "";
while ($zaznam = mysql_fetch_array($vysledek)) {
$zaz = $zaznam['jazyk'];
$out .= "<option>".$zaz."</option>";
}
$vys = utf8_decode($out);
echo $vys;
}
jQuery:
$("#sel_had_zem").change(function(){
var select_had = $("#sel_had_zem option:selected").text();
console.log(select_had);
$.ajax({
data:{'select_had':select_had},
success: function(data){
console.log(data);
$("#sel_had_jaz option").nextAll().remove();
$("#sel_had_jaz").append(data);
},
error: function(){
alert('No server response');
}
});
});
You'll need to set the charset in your MySQL connection and not in the MySQL query. If you're using MySQLi then you can mysqli_set_charset() built-in PHP function. However, if you're using PDO then you can use it like this:
new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8;', USERNAME, PASSWORD);
You can find more information about the mysqli_set_charset() function here:
http://www.w3schools.com/php/func_mysqli_set_charset.asp
Note: Please, also ensure you've added the <meta charset="UTF-8"> in your HEAD tag.
Try changing the following..
dataType: 'html'
to
dataType: 'application/html'
keep
contentType: 'charset=utf8'
and add <?php header('Content-Type: application/html; charset=utf8'); ?> to the top of your pages.
For error reporting put error_reporting(E_ALL); at the top of your page as well. If any errors arise, post the code for that line, and post the error message in your OP post.
For your error
Resource interpreted as Document but transferred with MIME type application/html
In your request header, you have sent Content-Type: html which means that you'd like to interpret the response as HTML. Now if even server send you PDF files, your browser tries to understand it as HTML. That's the problem.
So need some info as to what exactly you're trying to send and what is the recieving end doing with this data?
You want to set the output from the PHP-page to UTF-8 and correct MIME-type:
mysql_query("SET NAMES utf8");
header( 'Content-Type: text/html; charset=utf-8' );
echo $sql_result;
exit;
This should fix the issue!

Ajax sends wrong charset

Ajax is sending to PHP
Ĺ asija-kabina
Instead of
Šasija-kabina
While I did declare the charset everwhere.
In the head of the html file I've got this:
<meta charset="ISO-8859-2">
In the PHP file I've got this:
header('Content-Type: text/html; charset=latin2');
And this is my ajax function where "str" is a json array:
function updateField(str, id, prevvalue, value, vehicletype){
$.ajax({
type: "get",
url: "inc/ajax/form_rest.php",
data: { q:str, prevvalue:prevvalue, value:value, vehicletype:vehicletype },
contentType: "application/json;charset=latin2",
success: function(html) {
$('#'+id).html(html);
}
})
.done(function(){
$("#"+id).removeAttr("disabled");
if($("#"+id+" option").length == 2){
$("#"+id).val($("#"+id+" option:last-child").val()).change();
}
if($("#"+id+" option:last-child").val() == ""){
$("#"+id).attr("disabled", "disabled");
}
});
}
Nevertheless I am getting the wrong output. Can anyone help me with this?
I think you need to use the correct ISO name for the character set, e.g. change:
contentType: "application/json;charset=latin2",
to
contentType: "application/json;charset=ISO-8859-2",
I also think that using anything other than UTF-8 is going to get you in more trouble later in your project as json_encode in PHP really only supports UTF-8.
do you use an external javascript file for this?, I think you need also to set the character set for the inclusion of the javascript file
<script src="myscripts.js" charset="latin2"></script>
but I really recommend you to use UTF-8 both on server and client side scripts

jQuery / AJAX / php encoding nightmare

First of all, my database encoding is utf-8.
I must send the string Fußball to index.php via the POST method. When I send it using an HTML form with action="index.php", it is sent as Fu%DFball and to return it correctly I use htmlentities() on the php file. It works great. The problem starts when I try to send it using jQuery/AJAX.
$("#Form").submit(function() {
$.ajax({
type: "POST",
dataType : "text",
url: "index.php", //Does the validation
data: $("#Form").serialize(),
success: function(data) {
alert(data)
},
});
return false;
});
It is sent as Fu%C3%9Fball and returned as Fuà and I tried everything to decode it or send it in a different way. Here is what is returned in various scenarios:
Sending normally, with htmlentities() on the php file:
FuÃ
Sending normally, without htmlentities() or with htmlspecialchars() on the php file
Fußball
Sending normally, with utf8_decode() on the php file
Fu
Using escape(), encodeURIComponent() or contentType: "utf-8" on the jQuery script before sending the string makes the form to be submitted in a way the .php file can't understand, but not only that, it still sends the string as Fu%C3%9Fball.
I also used the proper command for each file type to encode all my documents as utf-8, which didn't make any difference so I assume it was all utf-8 to start with.
Make sure your web page's encoding is also UTF-8.
If it is ISO-8859-1 by default, it'll parse UTF-8 characters wrongly, as experienced by you.
To check, look in your browser's "encoding" menu when opening the page: That's the final word on what encoding is used.
It could be that your server is configured to output ISO-8859-1 content type headers for HTML files. See How to change the default encoding to UTF-8 for Apache? for how to fix that.

JSON.parse fails in jQuery when PHP response-header contains "application/json"

I'm getting a bit of a headache trying to figure this one out. To request some json-data from a PHP-script via Ajax, I'm using the jQuery function:
$.ajax({
type: 'GET',
cache: 'false',
url: ajaxUrl,
data: dataString,
success: updatePage
});
If I don't set content-type in the PHP header to:
header('Content-type: application/json');
Then my response from the server looks like this:
{"content":"new content"}
And the content-type is automatically set to text/html. When dataType in the jQuery ajax options is unset, it uses a default of 'intelligent guessing'. I'm strongly assuming that jQuery recognizes the response-data as json because updatePage is parsed an object. updatePage uses the JSON js library(json2.js), and does this:
function updatePage(data) {
$dataObj = JSON.parse(data);
}
When the function is called upon ajax succes, everything works fine. No errors.
Here's the strange thing, if I set my header to application/json as above, JSON.parse suddenly reports an error. The exact same error happens if i set my dataType to 'json' in the jQuery ajax request. The response I get from the PHP script when changing these things looks exactly like the one above. The error looks like this in Firebug:
JSON.parse
$dataObj = JSON.parse(data);
Kind of a long one, sorry, but If anyone knows what is wrong their help is greatly appreciated. Thanks for your time.
It's because you end up trying to double-parse the return value.
Both the explicit json data type and usage of the application/json MIME type cause jQuery to parse the returned string into a JavaScript object for you.
So, your usage of JSON.parse(), in these cases, is superfluous.

Categories