jQuery ajax special characters problem - php

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.

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.

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!

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.

Populating select list from AJAX JSON result data

Hello stackoverflow developer,
First of all, sorry if I couldn't find a solution, but I've been trying for a while now.
I'm not sure if my approach is the best one, so, if there's an alternative to AJAX and/JSON, please feel free to suggest it.
I'm creating a tourist guide website where registered users will include their resorts, restaurants and tourist attractions according to region and state. I'm using Joomla! and Seblod for this (with some custom PHP, MySQL, Javascript and AJAX). Since I don't want to manually create 27 dynamic selects, I've been trying selecting the list of registered beaches (to which resorts and tourist attractions must be related to) with PHP/AJAX/JSON/JQuery.
Everything works except populating the beach list, and I don't know what the problem is. I've tried multiple ways to append, create or add the options but nothing happens.
The PHP/JSON result is :
`
[{"id":"17","title":"Porto+de+Galinhas"},{"id":"18","title":"Serrambi"},{"id":"19","title":"Tamandar%E9"}]
`
It's the result of this PHP script:
`
if($_GET['q'] == 'beaches'){
$praiaSQL = sprintf("SELECT * FROM vp_content AS c LEFT JOIN vp_cck_store_item_content AS v ON c.id = v.id WHERE c.catid = 10 AND v.cck = 'praia' AND v.venue_state = '%s' ORDER BY c.title ASC;", $_GET['s']);
$query = mysqli_query($connection, $praiaSQL);
$praia = array();
while($results = mysqli_fetch_assoc($query)){
array_push($praia, array('id' => $results['id'], 'title' => urlencode($results['title'])));
}
echo json_encode($praia);
}
`
I also need a solution to handle accented characters. I'm trying urlencode here and decode in the JQuery, but may be the problem. When I left it as the original data, when there were accented characters the result item was empty.
This is the relevant JQuery that handles the result (where x = the select and u = the URL to get the AJAX JSON result - I've commented where the problem is in the code):
`
function setBeachList(x,u){
var theDiv = "#cck1r_" + x;
var theSelect = "#" + x;
$j(theSelect).children("option:not(:first)").remove();
$j.ajax({
url: u,
contentType: "application/json;charset=UTF-8",
success: function(data){
if(data.length){
/****
This is where I'm stuck, as I can't find a way to make sure the
data is actually being treated/handled.
I've tried alerts and all sorts of other options to populate the
select.
I know it's being called because the before: and after: functions
are working.
*****/
/*
$j.each(data, function(k, v){
var o = new Option();
var newTitle = urldecode(v.title);
$j(o).html(newTitle).val(v.id);
$j(theSelect).append(o);
});
*/
var htm = '';
for (var i = 0; i '+urldecode(data[i].title)+'';
}
$j(theSelect).html(htm);
}
},
beforeSend: function(){
$j(theDiv).hide();
},
complete: function(){
$j(theDiv).show();
},
dataType: 'json',
});
}
`
Thank you for the time and patience, I'm not an expert at any of this (not exactly a newbie, but close...).
urldecode is not a javascript function,
you can use decodeURIComponent instead of it.
it's working when you change it,
http://jsfiddle.net/MzMPK/1/
UPDATE:
I think your problem is about trying to encode accented chars, It should work without encoding them, if your all encodings are set as UTF-8.
This is a common JSON parsing silent error.
If the JSON is not well formatted, the ajax request will fail silently.
The second most common cause of this problem is the encoding. Make sure you are using UTF-8 in the page you're calling the AJAX and on the script that returns the data.
Your problem with accented data can be resolved by not encoding the data on the server side, thus not needing to unenconde on the client side.
To answer my own question:
Since I'm not and AJAX/JSON expert, I don't know if it's the expected behavior, but the responding page, which generates the AJAX result, cannot have different data than the one expected. Since I had left a regions' output, the requesting page had problems dealing with it somehow. Once I removed the unnecessary data, the select list got updated fine.
That was something I forgot to mention in my post, because I assumed that it was fine to have more than one result in the page. Using Firebug to check the code, the request was being brought fine.
Thank you all for your time, and sorry for the inconvenience...
I had to add htmlentities to the responding page, as accents returned null, although I explicitly have UTF-8 on every file...

Mysql not retaining line breaks from Jquery ajax post?

I've got a PHP/Mysql app that lets users post text from a form. When I insert text from an HTML textarea into my mysql table, it's not keeping the carriage returns/line breaks. The text is not stored in the DB as "Hey SO, \n This is a new line". It's stored with white space in the column (exactly like it's typed), but there is no way for me to output it with nl2br() and keep the breaks. I'm escaping before inserting the text like so:
$foo_text = mysql_real_escape_string(ucfirst($_POST['foo_text']));
But even if I remove everything and just use the POST parameter, it still does the same thing. Would this have anything to do with me serializing and posting this form via ajax (I'm using JQUERY)? I found this on stackoverflow, but I don't really see a solution. I'm posting with:
$.ajax({
type: "POST",
url: "insertFooBar.php",
data: $("#foo_form").serialize(),
success: function(msg) {
ETC...
}
})
Is there something really obvious I'm missing here? I'm stuck...
Thanks in advance for any help!
The problem is that serialization should encode a line break as %D0%DA, but jQuery encodes it as %0A.
The only (graceless) solution i found was to get the form serialized string, then modify it with a replacement function such as :
function keepLB (str) {
var reg=new RegExp("(%0A)", "g");
return str.replace(reg,"%0D$1");
}
Once the serialized string is modified, i send it using the $.post() function.
Hope it will help !
Thanks for the answers. I ended up removing the serialize() and sending each parameter manually as a string. I added $("#foo_bar").replace( /\n/g, '<br>' )) to my textarea as a workaround and now I'm getting my breaks. Wish I didn't have to hack this to make it work, but it gets the job done.
I never got any problems inserting data from a HTML Form into database, either the form submitted normally or using AJAX.
Have you try to submit the form without AJAX? What is the result? I want to suggest you to use jQuery form plugins so you don't have to do the AJAX request manually.
I'm also want to suggest you to use AdoDB to save the data into database. This library provide a great cross-database abstraction. I haven't found any problems when insert/update the data, all value escaping is done automatically. Here is the example way to do update using AdoDB:
$data['foo_text'] = ucfirst($_POST['foo_text']);
$adodb->AutoExecute($tablename, $data, 'UPDATE', "id=$id");
I hope this libraries will help you.

Categories