1

I try to redirect user through a new page, but

window.location =  

or

window.location.replace()

or

window.location.href = 

Append the new url to current url and doen't replace it

Here is my code

<div id="header">

    <script type="text/javascript">

    function set_lang_as_en() {
        if (location.protocole) {
            window.location = location.protocole + '//' + location.host + location.pathname + '?lang=en';
        } else {
            window.location.href = location.host + location.pathname + '?lang=en';
        }
    }

    function set_lang_as_fr() {
        if (location.protocole) {
            window.location = location.protocole + '//' + location.host + location.pathname + '?lang=fr';
        } else {
            window.location.href = location.host + location.pathname + '?lang=fr';
        }
    }

    </script>

    <a href="#" onclick="set_lang_as_en();return false;" >
        <img src="images/lang/usa.png" title="Change langage to english"></img></a>

    <a href="#" onclick="set_lang_as_fr();return false;" >
        <img src="images/lang/france.png" title="Changer la langue pour français">    </img></a>

    <span id="title">TITLE</span>
</div>

<hr />

for example if my url is

http://127.0.0.1/~user/index.php 

and I click on the link, then my new url is like :

http://127.0.0.1/~user/127.0.0.1/~user/index.php?lang=en

Thanks for reading

1 Answer 1

3

Typo at location.protocole - should be location.protocol.

              //here ↓
if (location.protocole) {
     window.location = location.protocole + '//' + location.host + location.pathname + '?lang=en';
                             //and here ↑

In both of your functions.

Since we're at it, simplifying your code a bit with location.search and drying it up we get:

function set_lang(lang) {
     location.search = '?lang=' + lang;
}

Then you can call it with set_lang('fr') and set_lang('en').

This will only update the query string part of the URL, keeping the same protocol, hostname and pathname.

Sign up to request clarification or add additional context in comments.

2 Comments

You right, it why I needed "if", I'll accept your answer when I'll could. This kind of error that's pretty hard to debug, thanks
@Epitouille No problem, I've updated the answer with a simpler solution as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.