Modify URL parameters using history.pushState()

Utilizing history.pushState, I am adding several parameters to the current page URL after performing an AJAX request. Now, based on user interaction on the same page, I need to update the URL once again with either the same set of parameters or additional ones. My code snippet looks like this:

var pageUrl = window.location.href + "?" + queryString;
window.history.pushState('','',pageUrl);

The 'queryString' variable holds my list of query parameters.

  • For instance, the initial page URL is:
  • After the first AJAX call on the same page, the URL should be:
  • Following a second AJAX call on the same page, the URL could look like:

However, using the above code results in the parameters being added to the URL alongside existing ones, leading to duplication as shown below after the second AJAX call:

Is there a way to replace the parameters in the URL before pushing it to the History object, or is there a better approach to achieving this functionality in JavaScript (using jQuery)?

Answer №1

It is my understanding that the solution entails eliminating window.location.href and retaining '?' +.

var currentUrl = '?' + queryDetails;
window.history.pushState('', '', currentUrl);

Answer №2

Use this function for updating URL parameters:

function updateUrlParameter(param, value) {
    const regExp = new RegExp(param + "(.+?)(&|$)", "g");
    const newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
    window.history.pushState("", "", newUrl);
}

Note: A simpler solution is presented below. It works even if the parameter is not currently in the URL. Please be aware that it's not compatible with Internet Explorer.

function setQueryStringParameter(name, value) {
    const params = new URLSearchParams(window.location.search);
    params.set(name, value);
    window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
}

Answer №3

If you want to manipulate the parameters of a URL while keeping the last part intact, you can achieve this by creating a new URL object:

// For example, let's take the URL: sample.com/testpage/test

var url = new URL(window.location);
url.searchParams.set('foo', 'bar');
window.history.pushState({}, '', url);

// The result will be: sample.com/testpage/test?foo=bar

// If you wish to remove only the parameter, you can do so like this:
url.searchParams.delete('foo');

Answer №4

Updating query parameters within the URL

This specific approach differs from other solutions by avoiding the use of regular expressions and string concatenations.

Parameters:

  • paramName - specifies the name of the query parameter as a string.
  • paramValue - represents the value associated with the parameter as a string.
  • addNew - a boolean flag that determines whether to always add a new parameter or update an existing one. When set to true, it ensures multiple parameters with the same name can be included in the query.
function modifyQueryString(paramName, paramValue, addNew=false) {
    const currentURL = new URL(window.document.URL);
    if (addNew) currentURL.searchParams.append(paramName, paramValue);
    else currentURL.searchParams.set(paramName, paramValue);
    window.history.replaceState(null, "", currentURL.toString());
}

Answer №5

const baseURL =
      location.protocol +
      "//" +
      location.host +
      location.pathname;
    console.log("baseURL : " + baseURL);
    history.pushState(undefined, undefined, baseURL + "?" + parameters);

Answer №6

To easily update my route, I found that by adding window.location.search at the end works like a charm:

If we have defined strings for user.id and post.id:

window.history.replaceState(
  null,
  "",
  `/users/${user.id}/${post.id}${window.location.search}`,
);

Referencing the definition of window.location.search

It retrieves the query portion of the URL in the Location object (including the leading "?" if not empty). It can also be modified to go to the same URL with an altered query (ignoring the leading "?").

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

Can you explain the contrast between uploading files with FileReader versus FormData?

When it comes to uploading files using Ajax (XHR2), there are two different approaches available. The first method involves reading the file content as an array buffer or a binary string and then streaming it using the XHR send method, like demonstrated he ...

Modifying button text with jQuery is not feasible

I'm facing a challenge with jQuery and I need the help of experienced wizards. I have a Squarespace page here: . However, changing the innerHTML of a button using jQuery seems to be escaping my grasp. My goal is to change the text in the "Add to car ...

Passing component properties using spaces in VueJS is a simple and effective

I am encountering an issue where I want to pass component props from my view, but I am facing a challenge due to the presence of a space in the value. This causes Vue to return the following error: vendor.js:695 [Vue warn]: Error compiling template: - inva ...

How to manage form submissions in Vue.js using inputs within child components

I'm working on a parent component that acts as a form. This form consists of multiple child components, each containing input fields. <template> <div class="form"> <generalData v-model="input" /> <textAreas v- ...

How to use jQuery to update a text input field based on a selected <select> dropdown option

Hi there, I could really use some help with this issue... Here's the problem - I need to change the value of a textbox within a table based on the selection of an option in a dropdown. Here's a simplified version of what I mean: <select id= ...

Executing JavaScript code within ASP.NET Visual Basic

My current web application uses jQuery and JavaScript, but I want to add more features that are supported in ASP.net VB. However, I am unsure if the JavaScript can run after the VB code. Essentially, I would like the web app to follow this sequence: ...

New Relic identifies mysterious delays caused by MongoDB's findOne method

After setting up newrelic to pinpoint the bottlenecks in my app, I discovered a major issue that has left me stumped. The source of most delays seems to be mongoDB user.findOne, but the biggest challenge is locating where in the code this delay is occurri ...

"415 (Unsupported Media Type) encountered when making a POST request in a REST API

I've encountered an issue with a React component where a checkbox triggers a POST request to a REST API with a single parameter. Despite setting a breakpoint in the WebAPI code, it's not being hit and I'm receiving a 415 Unsupported Media Ty ...

Creating a file structure for JavaScript files in a Vue CLI project

When structuring my Vue CLI project, I'm struggling to find clear documentation on best practices. Currently, I have 10 modules each with an associated JS file. My approach so far involves organizing all the pages in my router.js within a views direc ...

Inquiry regarding modules in Javascript/Typescript: export/import and declarations of functions/objects

I'm fresh to the realm of TypeScript and modules. I have here a file/module that has got me puzzled, and I could really use some guidance on deciphering it: export default function MyAdapter (client: Pool): AdapterType { return { async foo ( ...

I could use some assistance with iterating through an array that is passed as a parameter to a function

Compute the product of parameter b and each element in the array. This code snippet currently only returns 25. This is because element a[0], which is "5", is being multiplied by argument b, which is also "5". The desired output should be ...

What is the method for including the sources directory within the require() scope in npm?

Upon examining my directory structure, the following layout is revealed: package.json /src a.js /test test_a.js The contents of package.json are as follows: { "name": "foo", "scripts": { "test": "mocha" }, "devDependencies": { "mocha ...

Requesting the user to repeatedly input their birth year until it is less than the current year

Can anyone help me figure out how to display a prompt until the user enters a birth year that is less than the current year? I've tried using a loop in my code, but I'm having trouble getting it right. Any assistance would be greatly appreciated. ...

Validating Inputs with an Array of Values in my Angular 2 Application

I have been exploring ways to retrieve data from an array of values instead of a single value when using [(ngModel)] binding in my Angular 2 application. The current setup functions perfectly with a single value, as shown below. The data is pulled from the ...

Troubleshooting React and NodeJs Fetch Problem

I am currently working on retrieving data from my API, which is functioning properly. The API endpoint I am trying to fetch results from is http://localhost:5000/api/continents. {"data":[{"continentId":3,"CName":"Atlantis"},{"continentId":2,"CName":"Devia ...

A guide on setting up ExpressJS Error Handling to display custom error messages based on the corresponding HTTP Status codes

I am struggling to figure out how to implement this task. You need to create an error on the /error path and pass it to the next function. Make sure to use appropriate error status codes for displaying different types of error messages. I attempted using ...

Changing the Material UI imported Icon on click - a step-by-step guide

Hey there, I'm currently working with React JS and Redux. I have a challenge where I need to change the star outline icon to a filled star icon on click. The icon is located just after emailRow in the emailRow__options section. Can someone assist me w ...

What could be causing my webpage to automatically refresh following a POST request in NodeJS?

Utilizing the express framework alongside NodeJS, I have encountered an issue where my client webpage refreshes after making a POST request that triggers a python script and returns a JSON object to the client. My dilemma lies in preventing this automatic ...

You can install the precise version of a package as mentioned in package.json using npm

At this moment, executing the command npm install will download the latest versions of packages. Is there a way to install the exact versions specified in the package.json file? ...

Incorporating a JavaScript npm module within a TypeScript webpack application

I am interested in incorporating the cesium-navigation JavaScript package into my project. The package can be installed via npm and node. However, my project utilizes webpack and TypeScript instead of plain JavaScript. Unfortunately, the package is not fou ...