The following parameter adds a language to my website:
if(isset($_COOKIE['language'])){
if($_COOKIE['language']==='en'){
$WEBSITE_TITLE = " | SITE EN";
$LANG = 'en';
$language = "en";
}elseif($_COOKIE['language']==='es'){
$WEBSITE_TITLE = " | SITE ES";
$LANG = 'es';
$language = "es";
}
} else {
$WEBSITE_TITLE = " | SITE EN";
$LANG = 'en';
$language = "en";
}
And through Ajax I can change the language of my website either in Spanish or English:
$(function() {
$(".lang").click(function(e) {
e.preventDefault();
var language = $(this).attr('data-lang');
var postData={lang: language};
var request = $.ajax({
method : 'POST',
url : 'language.ini.php',
data : postData,
dataType: "html"
});
request.done(function(data) {
//$("html").html(data);
//location.reload();
//location.href = '/index.php';
setTimeout(function(){
location.reload();
},100);
});
request.fail(function(jqXHR, textStatus) {
alert("Error!: " + textStatus);
});
});
});
The data sent by Ajax is received through the following parameters:
if (isset($_POST['lang'])) {
$lang = $_POST['lang'] ?: '';
if ($lang === "en") {
setcookie ('language', 'en', time()+60*60*24*365, '/', 'example.com');
} elseif ($lang === "es") {
setcookie ('language', 'es', time()+60*60*24*365, '/', 'example.com');
}
}
But the error is when I try to change the language in a url with several folders or directories:
example.com/es/folders2/folders3/folders4/url-of-article/
Currently the code to change the language only works for me on these pages:
example.com
example.com/index.php
Change dataType: "html"
to dataType: "json"
and add console.error(jqXHR);
in to your fail function goto console see what you get.
You probably having problem with data type.
I tested this and it works fine for me :
$(function() {
$(".lang").click(function(e) {
e.preventDefault();
var language = $(this).attr('data-lang');
var postData={lang: language};
var request = $.ajax({
method : 'POST',
url : 'language.ini.php',
data : language,
dataType: "JSON"
});
request.done(function(data) {
//$("html").html(data);
//location.reload();
//location.href = '/index.php';
$("#results").html(data); //show data
setTimeout(function(){
location.reload();
},100);
});
request.fail(function(jqXHR, textStatus) {
console.error(jqXHR);
alert("Error!: " + textStatus);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="lang"> click me </div>
<div id="result"> </div> // Conent will show in this div.