In my symfony 2 application, I am translating a string in a controller, from a yaml file, and sending it via ajax.
Then in my ajax function, I am parsing the response with JSON
The issue I have is the string that is being output by the translator is not in UTF8. Why? It is in the right format when I call the filter | trans in my templates.
Also, accentuated letters written in my controller are correctly sent in UTF8, it really seems to come from the translating component.
The workaround I found is to encode in UTF8 after it is translated in my controller, send it via ajax, then decode UTF8 in javascript. But it's not super clean plus I can get "this is not a URI" errors.
How can I have the translator output a UTF8 string in my controller ?
My yaml:
rights:
is_boss: Tout éditer, voir, supprimer
My controller:
$message= strtolower($translator->trans('rights.is_boss', array(), 'backend_pages'));
$response = array(
'message' => utf8_encode($message)
);
return new JsonResponse($this->get('serializer')->serialize($response, 'json'));
My view:
$.ajax({
type : 'POST',
url : '{{ path('manage_rights', {'associate' : associate.id }) }}',
data: {right: right, parameter: parameter, value: value},
dataType: 'json'
}).done(function(response){
response = JSON.parse(response);
var message = decodeURIComponent(escape(response.message));
//do stuff
})
The error I get if I don't encode in UTF 8 is the following:
Your data could not be encoded because it contains invalid UTF8 characters. 500 Internal Server Error - RuntimeException in vendor\jms\serializer\src\JMS\Serializer\JsonSerializationVisitor.php at line 36 -
Precision:
//This does not output a proper UTF8 string. I get an error if I try to serialize it in JSON
$message= strtolower($translator->trans('rights.is_boss', array(), 'backend_pages'));
//In my twig, this does output a correct string with accentuated chars without weird symbols
<label>{{ ('rights.is_boss') | trans }}</label>