dynamic url query string manipulation with jquery

dynamic url query string manipulation with jquery
Learn how to update URL query string parameters dynamically without reloading the page using jQuery. This article provides a step-by-step guide and real-world examples to demonstrate the technique.

Modern web applications often require dynamic updates to the URL without reloading the entire page. This functionality allows users to bookmark or share specific states of the application and improves the overall user experience. In this article, we'll explore how to change the URL query string parameters using jQuery without reloading the page.

Consider a scenario where you have a web page with multiple filter options. Users can filter products based on category and price without reloading the page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Filter Products</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<h1>Filter Products</h1>

<select id="categoryFilter">
    <option value="">All Categories</option>
    <option value="electronics">Electronics</option>
    <option value="clothing">Clothing</option>
    <option value="books">Books</option>
</select>

<select id="priceFilter">
    <option value="">All Prices</option>
    <option value="low">Low</option>
    <option value="medium">Medium</option>
    <option value="high">High</option>
</select>

<button id="applyFilter">Apply Filter</button>

<script>
$(document).ready(function() {
    var urlParams = new URLSearchParams(window.location.search);
    var selectedCategory = urlParams.get('category');
    var selectedPrice = urlParams.get('price');

    if (selectedCategory) {
        $('#categoryFilter').val(selectedCategory);
    }

    if (selectedPrice) {
        $('#priceFilter').val(selectedPrice);
    }

    $('#applyFilter').click(function() {
        var selectedCategory = $('#categoryFilter').val();
        var selectedPrice = $('#priceFilter').val();
        var newQueryString = 'category=' + selectedCategory + '&price=' + selectedPrice;
        changeQueryStringWithoutReload(newQueryString);
    });
});

function changeQueryStringWithoutReload(newQueryString) {
    var newUrl;
    var baseUrl = window.location.protocol + '//' + window.location.host + window.location.pathname;
    newUrl = baseUrl + '?' + newQueryString;
    history.pushState({}, '', newUrl);
    console.log('New URL:', newUrl);
}
</script>

</body>
</html>

Changing the URL query string dynamically without reloading the page is a powerful technique that enhances user experience and provides better navigation within web applications. With the help of jQuery and the `history.pushState()` method, developers can easily implement this functionality in their web projects. We hope this article helps you understand and implement URL manipulation in your applications effectively.

Post a Comment

0 Comments