473,320 Members | 1,965 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Problem with latin characters when sending a form content with AJAX

xNephilimx
213 Expert 100+
lHi guys!
I'm having a little problem that's getting on my nerves, I couldn't find a solution, I also tryed googling it and I found nothing... (my field of expertise is in AS 2 and 3, but I still lack some JavaScript solid knowdlege)

The problem is that when I try to send a form's content with Ajax (I'm using the prototype library), for some reason the latin characters (accents and stuff, like áéíóú) turn a mess when I try to store them in a db, but not when I only display them with PHP. I tryed then to see if the problem was with the Ajax part, so I got rid of it and made a common submit with the form. That way worked perfectly, so this is why I think that the problem is there.

A phrase like this:
Probando acentos á é í ó ú
(That means "Trying accents á é í ó ú)

Ends up like this:
Probando acentos á é Ã* ó ú

May be is when I make the query string with the Form.serialize method. I don't know... I tryed using the decodeURI() with the query -decodeURI(Form.serialize)-, and it actually got better, but still not working.

The code so far is this (I will post only the vital code):

The form:
[HTML]
<form method="post" action="actions.php" id="post_form">
<p>Título:<br /><input type="text" name="postTitle" id="postTitle" style="width:100%" /></p>

<script type="text/javascript">
//<![CDATA[
var rte1 = new RichEditor("postText","100%",400,"<?=$_POST['postText']?>");
rte1.write('targetDiv');
//]]>
</script>
<input type="button" name="save" value="Guardar y Seguir Editando" />
<input type="button" name="publish" value="Publicar" />
</form>
[/HTML]

The RichText class is a class I developed that makes a rich text editor, it works perfectly so the error can't be dragged from there. Also, the issue I'm getting is also happening in the title, and that is a common text input.

The script:
Expand|Select|Wrap|Line Numbers
  1. var msg = $('message');
  2. msg.style.display = 'none';
  3.  
  4. var form = $('post_form');
  5. form.save.onclick = prepare;
  6. form.publish.onclick = prepare;
  7.  
  8. function prepare(e) {
  9.     var obj = e?e.target:window.event.srcElement;
  10.     submitForm(obj.name);
  11. }
  12.  
  13. function submitForm(method) {
  14.     var params = decodeURI(Form.serialize(form));
  15.     params += '&method=' + method;
  16.  
  17.     var req = new Ajax.Request('actions.php',{
  18.         method:'post',
  19.         parameters:params,
  20.         onLoading:loading,
  21.         onComplete:avisar
  22.     });
  23. }
  24.  
  25. function loading() {
  26.     msg.style.display = 'block';
  27.     msg.innerHTML = 'Guardando...';
  28.     Form.disable(form);
  29. }
  30.  
  31. function avisar(response) {
  32.     Form.enable(form);
  33.     msg.style.display = 'block';
  34.     msg.innerHTML = response.responseText;
  35. }
  36.  
The PHP:
[PHP]
include('config.php');
include('functions.php');

$section = $_POST['section'];
$method = $_POST['method'];

$postTitle = $_POST['postTitle'];
$postContent = $_POST['postText'];

if($section == "write_post") {
$sql = "INSERT INTO posts (
post_author,
post_date,
post_title,
post_content,
post_status,
post_comments,
post_category,
post_type
) ";

if($method == "save") {
$postStatus = 'draft';
} else if ($method == "publish") {
$postStatus = 'published';
}

$sql .= "VALUES(
1,
'',
'$postTitle',
'$postContent',
'$postStatus',
'open',
1,
'post'
)";

$dblink->createResultSet($sql, $db); //when inserting the data in the db all the latin characters are a hell of a mess
echo 'Tu post fue guardado con exito! ' . $postTitle; //but here here the $postTitle is displayed correctly
}
[/PHP]
($dblink is an instance of a class I programmed to manage db queries, it works alright, the problem only happens when I use the Ajax way to "submit" the form)

Also, my database has the latin1_general_ci collation, but I tried other variants and also UTF8 variants and all I got is a different mess each time, but a mess nontheless.... ^_^'

I'd really appreciate any help you can provide me.
Thanks a lot!

Best regards
The_Nephilim
Oct 23 '07 #1
7 10204
Ferris
101 100+
hi
You need to encode your URL before sending it to PHP page by javascript,but I have no idea how to decode it in PHP,maybe you needn't to do it cos' php can decode automatically just like asp.


my suggestion:
change


Expand|Select|Wrap|Line Numbers
  1. function submitForm(method) {
  2.     var params = decodeURI(Form.serialize(form))
into

Expand|Select|Wrap|Line Numbers
  1. function submitForm(method) {
  2.     var params = encodeURI(Form.serialize(form));

and try it again...



I also wrote a simple test page about encoding and decoding in Javascript,and it works with latin characters.I wish will help you. :)



[HTML]
<html>
<head>
<title>encode & decode in latin characters</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>
<script language=javascript>
function encode()
{
var str = document.getElementById("txt1").value;
if (str!="")
{
var result = encodeURI( str ); //ATTENTION!!!
document.getElementById("txt2").value = result;
alert ( str +"\nencode to\n"+result);
}
else
{
alert ("please input the origin url first,thanks.");
}
}
function decode()
{
var str = document.getElementById("txt2").value;
if (str!="")
{
var result = decodeURI( str ); //ATTENTION!!!
document.getElementById("txt3").value = result;
alert ( str +"\ndecode to\n"+result);
}
else
{
alert ("please input the encoded url first,thanks.");
}}
</script>
<body>
origin &nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" size="40" id="txt1" value="http://test.com/?param1=á é í ó ú&param2=á é í ó ú"/>
<br>
encoded url
<input type="text" size="40" id="txt2" value=""/>
<br>
decoded url
<input type="text" size="40" id="txt3" value=""/>
<br>
<input type="button" id="btnen" value="encode" onclick="javascript:encode();"/>
<input type="button" id="btnde" value="decode" onclick="javascript:decode();"/>
</body>
</html>
[/HTML]
Oct 23 '07 #2
xNephilimx
213 Expert 100+
Hi! Thanks for the reply!
I tryed without the decodeURI, and it's not working.
The thing with the encodeURI is that it also encodes the ampersands (&) that concatenates the data in the query string, and there's no way to decode that in php, because it doesn't recieve ir as a string, but as post data.

As I said before, the problem appears only when I save the data in a DB, when working only with PHP there is no problem. That's what gets me lost...

I'll try making the querystring myself to see if there's some kind of problem with the Form.serialize method of the prototype library.

Thanks anyways!!

Best regards,
The_Nephilim
Oct 23 '07 #3
Ferris
101 100+
hi

if php can read your querystring,it seems no problem in your client side code.

if the characters turns to mess in DB,you need to check the default charset in your DB settings and Apache php Server configure. if they are not the same charset , the mess will come up.

hope it helps.
Oct 24 '07 #4
xNephilimx
213 Expert 100+
Hi ferris, thanks.
The charset in my DB is latin1_general_ci
When I store the data without the ajax part it displays well, it only happens when using Ajax. That's the weird part.

Kind regards
The_Nephilim

hi

if php can read your querystring,it seems no problem in your client side code.

if the characters turns to mess in DB,you need to check the default charset in your DB settings and Apache php Server configure. if they are not the same charset , the mess will come up.

hope it helps.
Oct 24 '07 #5
xNephilimx
213 Expert 100+
I finally solved it, just changed the encoding of the pages to UTF-8.
Thanks for your help anyways!

Best regards,
The_Nephilim
Oct 30 '07 #6
w3rm
1
hi,

im having the same problem here....

where do you put the UTF-8 encode? in which pages?

thx
Feb 19 '08 #7
acoder
16,027 Expert Mod 8TB
hi,

im having the same problem here....

where do you put the UTF-8 encode? in which pages?

thx
Set the headers of the pages. If it's set properly on the server-side pages, use the setRequestHeader method of the XMLHttpRequest object.
Feb 20 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: Achim Domma | last post by:
Hi, I read a webpage via urllib2. The result of the 'read' call is of type 'str'. This string can be written to disc via file('out.html','w').write(html). Then I write the string into a...
10
by: Arne | last post by:
Since I am Swedish, I write website content mostly in Swedish language and using charset iso-8859-1. I have (just for testing) tried to use utf-8 on a test page (...
1
by: Markus Ernst | last post by:
Hi I wrote a function that "normalizes" strings for use in URLs in a UTF-8 encoded content administration application. After having removed the accents from latin characters I try to remove all...
5
by: vtreddy | last post by:
Hi All: In my application I am sending the input values through query string from a datagrid template column,I used URLEncode to encode the URL String, please find the input below, I am facing a...
4
by: imoschak | last post by:
Hi there i have a problem while parsing and xml file. The file is a backup from moodle (moodle.xml). When i open the file with one of my editors and setting Encoding to utf8 font courier standard...
2
by: Seguros Catatumbo | last post by:
Hi, i am trying to fill a dropdown menu with ajax, but the table contains latin characters. In mozilla i get a weird black character instead, and in internet explorer the whole code breaks because...
3
by: =?Utf-8?B?c2JwYXJzb25z?= | last post by:
I have a scenario where a string is sent in chunks to my app. I need to be able to identify certain tags in this partial string as it arrives. eg <DALFile>xxxxxxxxx</DALFile> I need to be able...
2
by: Gene | last post by:
Hi, I have problem with X-JSON. I am sending, in header, Polish chars, that are correct encoded in database, but when they came through header something wrong happen with encoding and I can only...
8
omerbutt
by: omerbutt | last post by:
hi there i have a form with multiple input (type/text ) fields and three inputs(type/file) fields i have to submit the form via ajax because i have multiple forms on this page ,you can say it is a...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.