Search code examples
phpjavascriptjquerytranslationgettext

Using gettext to translate an email inside an ajax call


I'm building a website in php and I handle the translation with gettext. So far everything is perfect but the website at some point sends an email to the user and I can't get the email to be translated.

I translate the website using .mo files and with a session I chose the language I'll be using:

    $lang=$_SESSION['lang'];
switch ($lang){
    case 'en':
        setlocale(LC_ALL, 'en_US.utf8'); 
        putenv('LC_ALL=en_US.utf8');
        bindtextdomain("estribo", "locale");
        bind_textdomain_codeset("estribo", 'UTF-8'); 
        textdomain("estribo");
    break;
    case 'es':
        putenv('LC_ALL=es_ES.utf8');
        setlocale(LC_ALL, 'es_ES.utf8');
        bindtextdomain("estribo", "locale");
        bind_textdomain_codeset("estribo", 'UTF-8'); 
        textdomain("estribo");
    break;
     }

Inside locale/en_US.utf8/estribo.mo I have all the strings translated and it works fine when I sue it anywhere in the page such as this:

   <a href="index.php"><?echo _("Index");?></a>

It will translate perfectly this way the rpoblem is when I do the same with the content of a variable (string) that I will later on send it via mail instead of print it on the screen.

This is my code for the email (checkout.php):

$message = _("Some text to send via email").": \n";
//a few more lines of 
$message .= _("Some more text").": \n";

mail($email, $subject, $message);

The way I get to the checkout.php is via ajax:

 function () {

    $.post('checkout.php', {
        cart: this.cart.items,
        total: this.format(this.total),
        quantity: this.quantity,
        shipping: $('select.shipping').val(),
        tipopago: $('input.tipopago').val(),
        customer: $('#checkout-form').serialize()
    }, function (result) {
            window.location.href = result;
        });
    return true;

}

Everything works and the strings are translated in the .mo file but the $message variable is not translating


Solution

  • the most likely reason I can think of:

    when you call checkout.php directly via AJAX, the environment for gettext is not configured.

    I assume that you have some kind of bootstrap process that takes place when you visit your website via a browser and use index.php or similar as entry point. If you point the AJAX call directly to checkout.php, this bootstrap process may be omitted.