0

I have a site that changes language according to the user's choice (at this time, only spanish and english), and stores the language in a variable that can be reached in JS via localStorage.getItem("varname").
I added a contact form that sends a email, and the ok/error message is stored in the php file - now, I needed to set the ok/error message to be shown in the two languages, so, the thing I did was to add the language var value to the js that calls the php, and, it works just fine when spanish is selected, but it opens a new tab in the browser with english, and also, it shows the whole path to the php file in the address bar (w/english).
Ok, now the code.
The languages bit -with the exception of the contact form- works just fine, for example, the options for a specific title would be:

<div class="title col-12">
    <h2 class="display-1" lang="es">Matríz</h2>
    <h2 class="display-1" lang="en">Head Offices</h2>
</div>

And then, in the js file this would show/hide the desired text:

var lang = localStorage.getItem("lang");
if (lang) {
    if (lang == "en") {
        $('[lang="en"]').show();
        $('[lang="es"]').hide();
    } else {
        $('[lang="es"]').show();
        $('[lang="en"]').hide();
    }
} else {
    $('[lang="en"]').hide();
    localStorage.setItem('lang', 'es');
}
$('.language').click(function() {
    $('[lang="es"]').toggle();
    $('[lang="en"]').toggle();
    if (lang === 'en') {
        localStorage.setItem('lang', 'es');
    } else {
        localStorage.setItem('lang', 'en');
    }
});

And, for the contact form, this is the js that calls the php:

$(function () {

    // idioma
    var lang = localStorage.getItem("lang");

    window.verifyRecaptchaCallback = function (response) {
    $('input[data-recaptcha]').val(response).trigger('change');
    };

    window.expiredRecaptchaCallback = function () {
        $('input[data-recaptcha]').val("").trigger('change');
    };

    // init the validator
    // validator files are included in the download package
    // otherwise download from http://1000hz.github.io/bootstrap-validator

    $('#contact-form').validator();


    // when the form is submitted
    $('#contact-form').on('submit', function (e) {

        // if the validator does not prevent form submit
        if (!e.isDefaultPrevented()) {
            var url = "path/in/server/to/contacto.php";

            // POST values in the background the the script URL
            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize() + '&lang=' + lang,
                success: function (data)
                {
                    // data = JSON object that contact.php returns

                    // we recieve the type of the message: success x danger and apply it to the
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    // let's compose Bootstrap alert box HTML
                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';

                    // If we have messageAlert and messageText
                    if (messageAlert && messageText) {
                        // inject the alert to .messages div in our form
                        $('#contact-form').find('.messages').html(alertBox);
                        // empty the form
                        $('#contact-form')[0].reset();
                        // reseteamos el Captcha
                        grecaptcha.reset();
                        // removemos el loader
                        $('.loader-fm').css('display', 'none');
                    } else {
                        var lang = localStorage.getItem("lang");
                        if (lang == "en") {
                            alert('Unknown error, please try again later, if the problem persists, notify the Administrator');
                        } else {
                            alert('Error desconocido, por favor intente más tarde, si persiste el problema, avise al Administrador');
                        }
                    }
                }
            });
            return false;
        } else {
            // caso haya un error ocultamos el loader
            $('.loader-fm').css('display', 'none');
        }
    });
});

And this sends the language var value just fine... in the contacto.php file this is how I tried to select the ok message:

if ($_POST["lang"] == "es") {
    $okMessage = 'Forma de Contacto Enviada, ¡Gracias! Pronto nos Pondremos en Contacto';
} else {
    $okMessage = 'Contact Form Sent, Thanks! We will be in Contact Soon';
}

Also tried, with a stranger result, to write a complete if/elseif:

if ($_POST["lang"] == "es") {
    $okMessage = 'Forma de Contacto Enviada, ¡Gracias! Pronto nos Pondremos en Contacto';
} elseif ($_POST["lang"] == "en") {
    $okMessage = 'Contact Form Sent, Thanks! We will be in Contact Soon';
}

This time, it won't even show the message in english, it just will just open a blank page in the browser.


After what @Twisty commented, I saw that when the lang var is set to "en", the value won't arrive, which resolve why when I use the elseif the page will show nothing (an also leaves the question, why is set to none, when inside the site it works, it changes the language...) - anyway, it doesn't says why it opens a new tab or page.
The data sent back to the AJAX in PHP happens like this, an array is created w/the ok/error message, this is the bit w/the ok:
$responseArray = array('type' => 'success', 'message' => $okMessage);

And then is sent back to AJAX:

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);
    header('Content-Type: application/json');
    echo $encoded;
}
else {
    echo $responseArray['message'];
}

What am I doing wrong?
Thanks in advance!

Disclaimer: the way the lang value is added to data in ajax was taken from this post and the language part is from a post of my own.

Gerardo
  • 81
  • 7

0 Answers0