0

I'm facing a little issue with a javascript script. I'm trying to make my website multi languages. All is set in database, and my select works on pages where the URLs don't have variables. Here is my script:

<script type="text/javascript">
    function submitForm() {
        var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
        window.location.href = window.location.pathname + '?lang=' + thelang;
    }
</script>

In the homepage case, it works, and change http://localhost/ by http://localhost/?lang=en

But when I have an URL with a variable already set, it replaces it. From http://localhost/modules/product/product.php?id=1 I have http://localhost/modules/product/product.php?lang=en and the result I'd like is:

http://localhost/modules/product/product.php?id=1&lang=en

How to fix the script to make it works in both cases, or add the varibale, or glue it with an existing one?

5
  • 1
    Look into URL and URLSearchParams for programmatic creation of URLs developer.mozilla.org/en-US/docs/Web/API/URL Commented Jul 8, 2019 at 15:10
  • try window.location.href += window.location.href.indexOf("?") !== -1 ? &lang=${thelang} : ?lang=${thelang} Commented Jul 8, 2019 at 15:10
  • 3
    Look at window.location.search here: developer.mozilla.org/en-US/docs/Web/API/Location Commented Jul 8, 2019 at 15:11
  • @nmak18 trying but syntax error, how to write it properly ? Commented Jul 8, 2019 at 15:43
  • try window.location.href += window.location.href.indexOf("?") !== -1 ? `&lang=${thelang}` : `?lang=${thelang}` - Sorry the template literals back-ticks got converted as code section Commented Jul 8, 2019 at 18:04

4 Answers 4

1

Try checking to see if querystring params already exist in the URL.

function submitForm() {
  var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;

  if (window.location.href.indexOf('?') >= 0) {
    // There are already querystring params in the URL. Append my new param.
    window.location.href = window.location.href + '&lang=' + thelang;
  } else {
    // There are not querystring params in the URL. Create my new param.
    window.location.href = window.location.href + '?lang=' + thelang;
  }
}

Update: Account for Subsequent Lang Changes

This assumes that the lang value will always be two characters.

function submitForm() {
  var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
  var newUrl = window.location.href;
  var langIndex = newUrl.indexOf('lang=');

  if (langIndex >= 0) {
    // Lang is already in the querystring params. Remove it.
    newUrl = newUrl.substr(0, langIndex) + newUrl.substring(langIndex + 8); // 8 is length of lang key/value pair + 1.
  }

  // Remove the final '?' or '&' character if there are no params remaining.
  newUrl = newUrl.endsWith('?') || newUrl.endsWith('&') ? newUrl.substr(0, newUrl.length - 1) : newUrl;

  newUrl = newUrl.indexOf('?') >= 0
    ? newUrl + '&lang=' + thelang  // There are already querystring params in the URL. Append my new param.
    : newUrl + '?lang=' + thelang; // There are not querystring params in the URL. Create my new param.

  window.location.href  = newUrl;
}
Sign up to request clarification or add additional context in comments.

3 Comments

What happens if the user changes languages two times, i.e. already have a 'lang' in the query string?
it's the only working solution, but as said Rickard Elimää, switching languages add them to the url: localhost/modules/product/…
Great point on subsequent lang changes. I'm hoping my update will work for you.
0

If I understand you correctly you want to add ?lang=en at the end. Unless there is already an id=1(or similar) there. So you could just add an if statement, looking if there is .php writen at the end. Not a very pretty solution but you are alreaady adding strings together so it doesn't matter

Comments

0

You can use the "search" element of window.location. See here for compatibility. You can then, concat the result with your desired parameter. BUT, you can do something way more complex (and secure) and check if there's already a parameter with that ID using a for + URLSearchParams.

const params = new URLSearchParams(window.location.search);

const paramsObj = Array.from(params.keys()).reduce(
    (acc, val) => ({ ...acc, [val]: params.get(val) }), {}
);

Comments

0

This should fix it:

var currentUrl = window.location.origin + window.location.pathname;
var newUrl = currentUrl + (currentUrl.includes('?') ? ('&lang=' + thelang) : ('?lang=' + thelang));
window.location.href = newUrl;

3 Comments

I tried, but only works on the root of url (localhost) as soon as I switch from a page (ex: localhost/modules/products/products.php), doesn't work anymore, strange!
@Artik i made a small edit.. try now if it works or not
I tried again with the update, but still doesn't work... damn ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.