Search code examples
htmlformsjspbootstrap-4http-get

Best way to pass query params on button clicks


I'm working on some code-base where an existing bootstrap button on a JSP page is like:

<nav class="navbar navbar-dark bg-primary">
    <div class="container-fluid pr0">
        <button class="btn btn-primary navbar-btn ml8" onclick="location.href ='/Configuration/AddConfiguration'">Add Configuration</button>
    </div>
</nav>

I want to pass some query params from here like - "/Configuration/AddConfiguration?program=${param.program}&location=${param.location}".

How should I pass these params in query?

NOTE: In another SO Post, it's mentioned that we can't pass query params with the action if the method is GET, otherwise for POST - I guess we can do that(not sure though).

What's the best practice that I can follow to pass these as query params then?

My thought is to make a form and then pass these query params as hidden fields of that form. But, to pass query params, is that the only way by creating forms and the passing params as hidden fields?


Solution

  • Seems like the SO post that you shared above is specific to just html forms.

    I added the JS function that first constructs the url params and then redirects to the desired URL.

    function redirectURL(pageURL, queryParams) {
        let query = Object.keys(queryParams).map(key => 
            `${key}=${encodeURIComponent(queryParams[key])}`).join('&');
        window.location.href = pageURL+'?'+query;
    };
    

    Refactored the button code to:

    <button class="btn btn-primary navbar-btn ml8" 
      onclick="redirectURL('/Configuration/AddConfiguration' {program:'${param.program}', marketplace:'${param.marketplace}'})">
      Add Configuration
    </button>