Pass two variables in the javascript url

Asked

Viewed 702 times

2

I have a website that has 5 different languages and when choosing a language the page text changes! For this I made a function:

<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><br/>

The problem is that now I have two id for that page, and I would like to know how to integrate in this function also the id.

For example the url should look something like this: localhost:8080/.../index.php?id=1&&lang=pt, but since I couldn’t pass the idto the variable, now the pages have stopped translating. The id I seek via GET

if (isset($_GET['id']) && !empty($_GET['id'])) 
{
    $id=$_GET['id'];
$id=mysqli_real_escape_string($link,$id);
    $query="SELECT * FROM local where local_id='".$id."'";
    $result=mysqli_query($link,$query);

    while ($row=mysqli_fetch_array($result)) {

        if ($row['local_id'] == 1)
        {
            ?> //AQUI FICA O HTML <?php } ?>


Languages are chosen through a select, what is happening is that you can no longer load, I can only update the page manually, changing the URL...

  • This ID is where? in the DOM or server?

  • Is on the server!

  • When you choose the language, the url loses the id, that’s it?

  • Hello @Leite!!! In this case you can’t even choose the language, simply when I choose one nothing happens, I can only change manually

  • Hello! What is the url you have before choosing a language and what it looks like after you choose it (confirms whether it changes or not)

  • Before choosing the language I have so http://localhost:8080/hoteljupiter/index.php?id=2 , then to choose the page gets all blank, but now I tried in my function so window.location.href = window.location.pathname +'?id=' + id +'&lang=' + thelang; , the page now when clicking on a language is no longer empty, only nothing happens, only if you change the language manually that is in the URL

  • @Milk is now that I read your question better, the link after choosing the language, the id disappears yes without making that change in my function, I apologize

  • Yes, that was the original problem. But with this change you made the url should be ?id=undefined&lang=pt, that? How does the url look? It doesn’t even change the page?

  • The url no longer changes with this change if I choose one of the languages, just nothing happens anymore!

Show 5 more comments

1 answer

1


Use this help function to add/change querystring values.

I’ve tried to comment to make you understand what’s happening at every step, but if you have any questions, feel free to ask.

function updateQuerystring(whatKey, newValue) {
    var exists = false; // vamos usar para ver se a chave já existe na querystring
    var qs = []; // a futura querystring (é um array, mas vamos tornar num string no fim)
    var __qs = window.location.search || ""; // a querystring actual ou uma string vazia, já deve ser caso nao exista, mas só para o caso..
    var _qs = __qs.substring(1).split("&"); // substring(1) remove o "?" do inicio e split("&") transforma num array, separando a string nos "&"

    for (var idx in _qs) { // por cada combinacao "chave=valor" na querystring
        var _kv = _qs[idx].split("="); // _qs[idx] é algo tipo "chave=valor" entao usamos split("=") para separar novamente
        var _key = _kv[0]; // 0 = chave
        var _value = _kv[1]; // 1 = valor

        if (_key === whatKey) { // se a _key for a que queremos alterar (a que foi passada a esta funcao), alteramos entao o valor
            _value = newValue;
            exists = true;
        }

        // metemos no tal novo array pra querystring, se for encontrado no if acima, entao _value vai ser o novo valor
        qs.push(_key + "=" + _value); // 
    }

    if (!exists) { // se nao encontramos durante o ciclo acima, entao adicionamos uma nova com os valores passados
        qs.push(whatKey + "=" + newValue);
    }

    // aqui retornamos (duh :P)
    return "?" + qs.join("&"); // juntamos o novo array com '&' e ficamos com uma string que podemos usar como querystring
}

Then in your function, you can call this and ask to update the parameter lang with what you received from <select>

function submitForm() {
    var thelang = var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
    var newquerystring = updateQuerystring("lang", thelang);
    window.location.href = window.location.pathname + newquerystring;
}
  • 1

    Thank you so much! It’s working perfectly

Browser other questions tagged

You are not signed in. Login or sign up in order to post.