How to set locale in ajax requests?

(this kind of issues is part of why my standard recommendation is to not have front end with two languages)

The core reason to the problem is that your ajax returns text. AJAX should be treated like API which provide machine level values which the front end translate to human text. When your code is built like that, you also end up with a better and more flexible code since your business logic is decoupled from the presentation one.

So what you should do is include a value to text translation in the JS handling the AJAX (if you short in development time, instead of integer type of values use the english text as a “value” instead of plain text.

This obviously bloats the JS therefor it is probably better to use the wp_localize_script to enqueue only what is needed based on context, but just having it in the JS itself is not the end of the world. (this obvious depends a lot on how do you get the actual translation, if it is in the usual wordpress .mo file, then the only option is the first one).

(for people that think wtf?, even if your site is in english you most likely need to do date time localization, and that can be done only on browser side, same goes for currency, thousands separator, so the idea of JS side localization, while not very popular in WP right now, have some real world problems that can be solved almost only in that way, therefor extending the localization in JS should be a natural thing)

Leave a Comment