webber
webber

Reputation: 1886

Post a UTF-8 string to a servlet using jquery

I'm trying to POSt a UTF-8 string to my servlet (hosted in TomCat) but the string read on the server side is not UTF-8. I've verified via firebug that the ajax header's content-type has the utf-8 encoding set. I'm posting "MÉXICO" to the server but I'm receiving "MÉXICO".

$.ajaxSetup({ 
    scriptCharset: "utf-8" , 
    contentType: "application/x-www-form-urlencoded; charset=UTF-8"
});


$.ajax({
  url: "SetData",
  type: 'POST',
  data: 'MÉXICO',
  success: function(){
      console.log('Data set');
  }
});

Here's the java code in the servlet

request.setCharacterEncoding("UTF-8");
BufferedReader reader = new BufferedReader( new InputStreamReader( request, "UTF-8" ) );        
char[] chr = new char[5];
reader.read( chr );
builder.append( chr );

UPDATE 1

I changed the posting data in js to encodeURIComponent('MÉXICO') but the server still reads "MÉXICO".

But, if I get the string value of encodeURIComponent('MÉXICO') i.e. 'M%C3%89XICO' it works! I'm zapped! Any idea why this should work?

$.ajax({
  url: "SetData",
  type: 'POST',
  //data: 'MÉXICO', ** does not work
  //data: encodeURIComponent('MÉXICO'),  ** does not work
  data: 'M%C3%89XICO',  //works !!!!
  success: function(){
      console.log('Data set');
  }
})

;

Upvotes: 1

Views: 3744

Answers (2)

elrado
elrado

Reputation: 5282

I don't understand what are you doing and what kind of request parameter are you sending. Shouldnt code be something like that:

...
data:{key:'MÉXICO'},
...

OR

...
data:{key:encodeURIComponent('MÉXICO')},
...

AND in servlet

...
request.getParameter('key')
...

OR

 stringURLDecoder.decode(
                             request.getParameter('key').toString(),
                             'UTF-8'
                        );

Or I didn't understand anything (If this is the case sorry :/)

Upvotes: 1

arunes
arunes

Reputation: 3524

Try encoding data value with encodeURIComponent()

data: encodeURIComponent('MÉXICO')

Source: JQuery AJAX is not sending UTF-8 to my server, only in IE

Upvotes: 1

Related Questions