Reputation: 21
I am trying to redirect English browsers to xyz.com/?lang=en
while letting Swedish ones stay on xyz.com
I have been trying :
var type=navigator.appName
if (type=="Netscape")
var lang = navigator.language
else
var lang = navigator.userLanguage
//cut down to first 2 chars of country code
var lang = lang.substr(0,2)
// Swedish
if (lang == "sv")
window.location.replace('????')
// if none of above (default to English or any other)
else
window.location.replace('xyz.com/?lang=en')
</script>
But I don't know how to write the Swedish URL since it's not a redirection as the default language is swedish... writing the xyz.com
gets me into a redirection loop
if ($_REQUEST["lang"] == "en")
{
echo '<div class="langlight"><a href="http://xyz.com/">Svenska</a></div>';
}
else
{
echo '<div class="langbold"><a href="http://xyz.com/">Svenska</a></div>';
}
if ($_REQUEST["lang"] == "en")
{
echo '<div class="langbold"><a href="http://xyz.com/">English</a></div>';
}
else
{
echo '<div class="langlight"><a href="xyz.com/">English</a></div>';
}
enter code here
Upvotes: 1
Views: 1125
Reputation: 196002
You are always checking the language from the navigator
.
This way everytime the page loads it will try to reload the page with the altered or not url.
You need to place a condition where it will not reload the page..
That should be when there is a URL parameter passed.
So check for the querystring as well and override the default if a value exists in the url.
<script type="text/javascript">
(function(undefined){
var queryString = {},
search = window.location.search.substring(1), // read the current querystring
searchItems = search.length?search.split('&'):[]; // and split it at the different params if any exist
for(var i = 0, len = searchItems.length; i < len; i++){ // for each parameter passed
var parts = searchItems[i].split('='); // split the key/value pair
queryString[parts[0].toLowerCase()] = parts[1]; // and store it to our queryString variable
}
if (queryString.lang === undefined){ // if there is no lang parameter passed do your checking otherwise skip this step completely and use the url lang parameter.
var type=navigator.appName, lang = '';
if (type=="Netscape") {
lang = navigator.language.substr(0,2);
} else {
lang = navigator.userLanguage.substr(0,2);
}
if (lang != "sv"){
if (searchItems.length){
window.location.replace(window.location.href + '&lang=en');
} else {
window.location.replace(window.location.href + '?lang=en');
}
}
}
}());
</script>
Notice: Although, as @missingno mentions in his comment to your question, this is best handled server-side than client-side.
Upvotes: 0
Reputation: 1115
if (lang !== "sv") {
window.location.replace(window.location.href + '?lang=en');
}
Upvotes: 2