Incorporate a PHP GET parameter through an onclick event to redirect using window.location in JavaScript when a button is

I am trying to modify the onclick event of buttons that look like this:

<button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2'">BUTTON 1</button>
<button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2'">BUTTON 2</button>

Is it possible to use javascript code to add &VAR3=3 to the existing onclick events in order to get the following result:

<button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2&VAR3=3'">BUTTON 1</button>
<button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2&VAR3=3'">BUTTON 2</button>

Answer №1

Suppose the user is currently on the URL "test_page.php?ID=1&ID2=2", this script will add &ID3=3 to the URL:

HTML:

<button class="btns" onclick="addParameter('ID3', '3')">Click Here</button>

JavaScript:

function addParameter(key, value)
{
    key = encodeURI(key); 
    value = encodeURI(value);
    var params = document.location.search.substr(1).split('&');
    var index = params.length; 
    var part; 
    while(index--) 
    {
       part = params[index].split('=');
       if (part[0] == key)
       {
          part[1] = value;
          params[index] = part.join('=');
          break;
       }
    }

    if(index < 0) 
    {
       params[params.length] = [key,value].join('=');
    }

    document.location.search = params.join('&'); 
}

Answer №2

HTML:

Inspired by Max Voisard, let's simplify the process assuming that the user is currently on the URL "page_test.php?VAR=1&VAR2=2".

<button class="buttons" onclick="insertParam('VAR3', '3')">BUTTON 1</button>

JS:

function insertParam(key, value)
{
  key   = encodeURI(key); 
  value = encodeURI(value);
  return window.location.href + `&${ key }=${ value }` 
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add a fresh item to a list using jQuery

Attempting to add a new list item using jQuery. In this scenario, the process works well, but when attempting to retrieve the value of an input field using .val(), no list item is created. http://www.example.com Code snippet: $(document).ready(functi ...

Exploring Request Parameters in SailsJS

I am facing an issue with logging requests in my Sails app. While I have managed to log the requests successfully, I am unable to log the parameters of the request. myRequestLogger: function(req, res, next) { if (sails.config.environment === & ...

How can I retrieve and manipulate the text within an option tag of a form using JavaScript?

<select name="products"> <option value=""> - Choose - </option> <option value="01">table</option> <option value="02">chair</option> <option value="03">book</option> <option value= ...

What could be causing the texture distortion in THREE.js?

I am encountering an issue with the textures loaded using the TextureLoader, as they seem to be causing tearing errors within the texture. Below is the code snippet I am using for the material: var textureName = "Melamine-wood-001"; var textureUrl = ...

What are the best practices for utilizing *ngIf?

In my Angular project, I am facing a challenge with using *ngIf. My app.component.html file handles both the login page and the dashboard. I want to hide the dashboard until the user logs in. To achieve this, I decided to use *ngIf. Here is how I implement ...

Exploring the React component life cycle: Understanding the distinction between render and return, and what happens post-return

This question pertains to the concepts surrounding react component life cycles. Below is an example code snippet provided as a general reference. const Modal = ({ className, variant, width, withCloseIcon, isOpen: propsIsOpen, onClose: tellParen ...

Updating DOM elements in AngularJS based on search results and user clicks

I have a query regarding my angular web app, which includes an ajax call for json-formatted dates to display them in a table. The app features a search input, two sorting buttons (for age or name), and a profile sidebar element. I have successfully update ...

PHP - WebCalendar - Show or Hide Field According to Selected Item in Dropdown List

Working with the WebCalendar app found at to make some personalized adjustments to how extra fields function. I've set up two additional fields: one is a dropdown list of counties, and the other is a text field. Within the dropdown list, there is an ...

Get the data from the files in the request using request.files in Node.js

Is there a way to read the content of a file (either a txt or CSV file) that a user uploads without saving it to local storage? I know I can save the file in an upload directory and then read it from storage. However, I'm wondering if there is a way ...

Issues with retrieving a result object from a MySQL query in NodeJS

I've been working on creating a logging system in NodeJS with a MySQL database. To establish the connection, I use the following code: const con = mysql.createConnection({ host : 'localhost', user : 'dbuser', passwor ...

What is the best way to showcase an array of objects in a table with two columns?

Looking to showcase an array of objects in a table with 2 columns. What's the simplest way to achieve this display? const columns = [ { subHeading: "A", subText: ["1", "2"] }, { subHeading: & ...

Having trouble with ng-click in my AngularJS Restful application

I was attempting to create CRUD operations in AngularJS. Unfortunately, I am facing an issue where my ng-click is not functioning properly. Below is the code for my list.html: <div class="container"> <input type="text" ng-controlle ...

Challenging glitch in the JavaScript code

My jQuery code seems to be functioning properly in online text editors like Fiddle and StackOverflow snippets. However, when I try to implement the same code in Brackets or view it on GitHub, the navbar scroll down animation fails to work as expected. You ...

Troubleshooting: Issues with jQuery Dropdown Menu

I'm currently working on a website that includes a settings feature with a button. My goal is to have the options and other links display in a dropdown menu when hovered over. Although I have written what I believe to be the correct code, it's no ...

Problem with Azure Table JavaScript Solution

When attempting to utilize JavaScript to access Azure Storage Tables, I encountered an error that reads: "Error getting status from the table: TypeError: tableServiceClient.getTableClient is not a function." Despite finding multiple successful examples onl ...

Synchronizing other components with a filtered query from the List in Admin-on-rest: Best practices

I am looking to incorporate the following structure into my page: 1. Cards displaying summaries (revenue, users, etc.) 2. Google Maps integration 3. List element Within the List element, there is filtering involved. I am struggling with how to utili ...

The CSS style of the Div element is not being displayed properly when embedded with JavaScript

Currently, I am working on a simple page for practice purposes. The main issue I am facing is with a div element that has a red border and a blue background. Inside the div, there is a script tag calling an external JavaScript file. Surprisingly, the JavaS ...

Issues with Internet Explorer's scaling functionality are preventing it from operating correctly

I've utilized d3 to create a map. Its width is dynamically set based on the parent div's (with the id "map") width, and its height is calculated with a ratio of 5/9 in relation to the width. The viewBox attribute has been defined as "0 0 width he ...

Execute a specialized function with imported modules and specified parameters

Within an npm project, I am looking to execute a custom function with arguments, or ideally provide it as a script in the package.json file like this: npm run custom-function "Hello, World". Currently, I have a file called src/myFunction.ts: import * as e ...

Unable to retrieve the sum total of all product items and display it in the designated text element

My product items are dynamically generated in a list. I have used the calculateItemTotal() method to determine the total for each item. Now, I need to sum up all these item totals and display the result in the total text field. However, instead of showing ...