ttncrch
ttncrch

Reputation: 7253

redirect javascript, replace url

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

Upvotes: 1

Views: 1155

Answers (1)

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70129

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.

Upvotes: 3

Related Questions