Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: ajax post and encoding

Tags:

jquery

I am unable to understand why I can't get a correct ISO-8859-1 charstet from the server answer. Being this a work on legacy code, i hardly could change charset encoding on the pages.

I make use of the JQuery call

$.post("server-side-code", {t:ctext, i:ioff, sid:sessionid},  
    function(data, status) {            
       $('#chk').append(data); 
     });

posting a textarea value created using javascript:

<form accept-charset='ISO-8859-1' method='post'>
<textarea cols='40' rows='8' id='commento'></textarea><br>
<input type='button' value='invia' id='submit'></form>

The server side script processing the request declares at its very top:

text/html; charset=ISO-8859-1

so, honestly, I can't figure out what else I should declare, in terms of encoding. This notwithstanding, the accented characters "àèéìòù" bounce back as: "à èéìòù" when placing the server answer in an HTML element

The source is saved as ascii. Tryng to do this to have rudimentary Html encoding on the variable to be posted does not solve:

ctext = escapeHTML(ctext);

function escapeHTML (str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}; 

Some idea?

Thanks!

like image 882
Daniel Avatar asked Jun 08 '09 14:06

Daniel


1 Answers

I have a better solution now. Both post and get works PERFECTLY. I'm working over tomcat who by default handle ISO 8859 stuff.

Web page properties:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

charset of the webpage inside the head.

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

Now, all my parameteres are escaped with escape function, I provided this solution before.

(function($) {$.fn.escape = function() {
    return escape(this.val());};})(jQuery);

Now, when sending the ajax request I set the contentType to this:

contentType : "application/x-www-form-urlencoded; charset=iso-8859-1"

And finally , when receiving the parameters at the servlet or any receiver I get a decoded parameter using this.

    public String getHttpParameter(String name) throws Exception {
    String value = this.getHttpRequest().getParameter(name);
    return value == null || value.isEmpty() ? value : URLDecoder.decode(value,"ISO-8859-1");
}

POST and GET works perfectly in IE 7 and 8 , SAFARI, CHROME and FIREFOX.

like image 144
Rodrigo Asensio Avatar answered Sep 16 '22 12:09

Rodrigo Asensio