473,545 Members | 2,081 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with latin characters when sending a form content with AJAX

xNephilimx
213 Recognized Expert New Member
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:10 0%" /></p>

<script type="text/javascript">
//<![CDATA[
var rte1 = new RichEditor("pos tText","100%",4 00,"<?=$_POST['postText']?>");
rte1.write('tar getDiv');
//]]>
</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('functi ons.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->createResultSe t($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 10233
Ferris
101 New Member
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=javasc ript>
function encode()
{
var str = document.getEle mentById("txt1" ).value;
if (str!="")
{
var result = encodeURI( str ); //ATTENTION!!!
document.getEle mentById("txt2" ).value = result;
alert ( str +"\nencode to\n"+result);
}
else
{
alert ("please input the origin url first,thanks.") ;
}
}
function decode()
{
var str = document.getEle mentById("txt2" ).value;
if (str!="")
{
var result = decodeURI( str ); //ATTENTION!!!
document.getEle mentById("txt3" ).value = result;
alert ( str +"\ndecode to\n"+result);
}
else
{
alert ("please input the encoded url first,thanks.") ;
}}
</script>
<body>
origin &nbsp;&nbsp;&nb sp;&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="javasc ript:encode();"/>
<input type="button" id="btnde" value="decode" onclick="javasc ript:decode();"/>
</body>
</html>
[/HTML]
Oct 23 '07 #2
xNephilimx
213 Recognized Expert New Member
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 New Member
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 Recognized Expert New Member
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 Recognized Expert New Member
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 New Member
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 Recognized Expert Moderator MVP
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 setRequestHeade r 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
4963
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 Memofield in an Access database, using adodbapi. If I read the text back I get a unicode string, which can not written to disc via file(...) due to encoding...
10
9682
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 ( http://w1.978.telia.com/~u97802964/test.html ) but the special Swedish characters don't come out right if I dont use entities for them. The Swedish characters in question is:...
1
6887
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 non-word characters from the string: // PCRE syntax: $string = preg_replace("/(+)/", "-", $string);
5
2400
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 problem when the input string contains ® character , Here from ASP.NET I am redirecting to the ASP based system,when I give same input from ASP based...
4
679
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 or greek characters the editor can see all greek strings contained within the file perfectly. On the other hand when i try to open it with php...
2
2252
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 if a word ends in a latin character then it ignores the <bri put on the end, therefore affecting my data logic. I am using results =...
3
2405
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 to have a regex that will capture the start, middle and end of this file based on the tags. The problem is that the end tag may not always be...
2
1919
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 see strange signs at page. I am using UTF-8. Please help, because all my ajax requests are based on sending data in header.
8
2679
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 contact_us.php page.Now i can get all the inputs at the other end else the input(type/file) i donot want a submit button what i want that some how io...
0
7468
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7401
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7656
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7808
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7423
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7757
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5329
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3450
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...

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.