jQuery / AJAX / php encoding nightmare - php

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.

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.

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

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

Decode $_POST data from ajax/Jquery serilized form

I submit a form using AJAX and JQuery.
serializedData = $form.serialize();
request = $.ajax({
url: "processData.php",
type: "post",
data: serializedData
});
The problem is when I use the data on processData.php the text is urlencoded.
cuando=Una+fecha+%C3%BAnica
I tried using php's urldecode() but it is not working. it's still urlencoded..
$cuando = $_POST['cuando'];
$cuando = urldecode($cuando);
Any suggestion? Thanks a lot!
Can't reproduce it..I made this:
<?php
echo urldecode('Una+fecha+%C3%BAnica');
Output is this:
Una fecha única
My only guess is that in your question you mean that your output is still what my input is, in that case you are somehow double urlencoding it on the other end
The form data is encoded in the same way as if it was a normal HTML form submission without Ajax, so there is nothing special to do, just use:
echo $_POST['cuando'];
PHP has already decoded and parsed the request body (post data).
First I tried changing the contentType attribute on JQuery $.ajax function, but it didn't work out:
$.ajax({
url: "insertar_datos.php",
type: "post",
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
data: serializedData
So, I found that there some issues at working with other charset encodings that are not UTF8 on JQuery-ajax.
http://forum.jquery.com/topic/serialize-problem-with-latin-1-iso-8859-1-and-solution
Then, I tried with no hope the php function utf8_decode():
utf8_decode($_POST['cuando']);
And it worked. what I found on this link is that:
"utf8_decode simply converts a string encoded in UTF-8 to ISO-8859-1. A more appropriate name for it would be utf8_to_iso88591. If your text is already encoded in ISO-8859-1, you do not need this function. If you don't want to use ISO-8859-1, you do not need this function."
So, if someone is using iso-8859-1 and is having some problems with ajax posted data. You can decode it for sure with utf8_decode(). Maybe there is an easier way to decode all data before post it, but as you can see it didn't worked to me.
If someone knows a better/more efficient way I'll choose your answer happily.
Hope it helps someone,
Regards!

PHP script appending html tag on JSON output

I have a ajax script written using jQuery calling a php script that is supposed to return a JSON string after a DB select. However, the php script is returning both the JSON string followed by a closing html tag. The page outputs nothing else (the only print command in the script is shown). I cannot find where that tag is being added. My server (running PHP5.4) is setup to prepend and append files, however I have that overridden. As a work around, I’m using exit() to abort any other output. The JSON is being built properly and I can go directly to the php script and see it just the string, but automatically wrapping it in properly html and body tags. With the exit() being called I can use the JSON properly. However, in the interest in cleaner code, I want to solve this problem for future development.
jq.info.js snippet:
function getCharInfo(chars_id){
$.ajax('/editor/jquery_info.php',{
data: {'chars_id': chars_id, 'qtype':'charsInfo' },
dataType: 'json',
cache: false,
jquery_info.php snippet:
foreach($chobj->char as $key=>$char){
$charInfo[$key] = parse_syn($char, 1);
}
$charInfo = json_encode($charInfo, JSON_UNESCAPED_UNICODE | JSON_FORCE_OBJECT);
print($charInfo);
exit;
The parse_syn function simply replaces html entities with UTF-8 equivalents (i.e. '&rquo;' to ’, '--' to '—' etc).
Any insight or settings to look into with PHP’s setup would be appreciated.

jQuery ajax special characters problem

Okay, so here is the problem:
I have a form on my php page. When a user has entered a name a presses submit a jQuery click event (on the submit button) collects then information and passes them on through $.ajax().
$.ajax({
url: "ajax/addGatheringSignup.php",
type: "POST",
async: true,
dataType: 'json',
data: {
"id": $_GET['id'],
"name": $signupNameInput.val()
},
success: function(jsonData){
if(jsonData[0].feedback == "ok"){
$signupForm = $('#singupform');
$signupForm.html('Signup successful!');
}else{
Alert(jsonData[0].feedback);
}
},
error: function(){
Alert("error alert");
}
});
As you can see the "name" field is the value from the name inputfield. But when i submit this to my php page (where I don't format anything within the text) its totally garbage in my MySql database. At the moment im trying to get the danish letters æ, ø and å to work.
Atm i know my mysql database are using UTF-8 and my meta-header for my index.php looks like this (every page is generated from the index.php page... ex index.php?page=random):
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
But nothings works. When i post: "æÆ-øØ-åÅ" to the database it saves as: "æÆ-øØ-åÅ".
anyone know what i have to do?
EDIT 1:
I can see that on a successful ajax submit the html i set $signupForm to (line 13. in the code above) displays wrong as well (it's normally some danish words where I write the danish chars mentioned)
EDIT 2 (found one solution):
I found a way. $.ajax() according to the jQuery doc, always parses data as UTF8. I don't know why this messed up my code, but when i added *utf8_decode($name)* to the add-function it parsed correct (so i guess my charset must have been set to ISO-8859-1 hidden somehow?). This just made it easier since i could then turn my old charset ISO-8859-1 back on again and remove all my utf8_encode() functions.
My last problem was the one presentated in "EDIT 1". Here i found a solution on how to convert UTF8 strings (again because of $.ajax()):
function decode_utf8( s ){
return decodeURIComponent( escape( s ) );
}
The problem might be in your database connection. It's communicating in a given charset as well.
See mysql_set_charset().
The data in the Ajax-POST is UTF8-encoded, so in your PHP script (where you write to the database), you need to do the following:
$name = utf8_decode($_POST['name']);
That way you can store æÆ-øØ-åÅ as æÆ-øØ-åÅ instead of the ASCII malformed æÆ-øØ-åÅ
Also your database needs to be on the appropriate collation (for instance latin1_swedish_ci)
I'm not sure but it sounds like you get mixed encoding types.
A page that is sent as UTF-8, but where input is transformed to ISO-8859-1 and store in a mysql UTF-8 encode table will fail.
You need to keep control on input ecodings type in relation to the type of encoding you have chosen to use as internal in php and external.
Try to see if this help you.
PHP messing with HTML Charset Encoding
http://www.tanzilo.com/2008/12/29/php-mysql-creating-a-website-in-your-local-language-smoothly/
function decode_utf8( s ){
return decodeURIComponent( escape( s ) );
}
is amazing
a good short form is
Name = decodeURIComponent( escape( Name ) );
it will solve 'ISO 8859-1 Characters' problem in ajax response.

Categories