Is there a way to send a variable from a URL to a script?

The abstract photography page on my photography website is accessed through a link like the following:

myphotographywebsite.com/abstract.html

This specific page utilizes a script that calls upon the Flickr API to retrieve my photos and information. The script includes lines similar to these:

    {
        photo_set: "abstract",
        tags: "best"
    },

Currently, my website has numerous pages and scripts, each dedicated to a different photo set. What I am aiming to achieve is consolidation by having one page with variables in the URL that can be utilized by a single script. For example, the link would look something like this:

myphotographywebsite.com/page.html?variable_1=abstract&variable_2=best

And the script would be modified as follows:

    {
        photo_set: "variable_1",
        tag: "variable_2"
    },

How can I successfully pass variables from the URL to a script functioning on that particular page?

Answer №1

If you're looking to extract query parameters from a page's URL, you can utilize the URL API. Check out the example below:

// Assume this is window.location.href in your actual code
let currentPageUrl = "https://examplewebsite.com/page.html?param1=value1&param2=value2";
let url = new URL(currentPageUrl);

// Create an object with extracted query parameters
let queryParams = {
  parameter1: url.searchParams.get('param1'),
  parameter2: url.searchParams.get('param2')
};

console.log(queryParams);

PS: Please note that the URL API may not be supported on Internet Explorer.

Answer №2

Sam shared a helpful link in his post that led me to the solution. Many thanks! For those interested, here is the link:

You can find the page he referenced by clicking on this URL:

After following the link, I discovered some code that I integrated into my script at the beginning like so:

// Extracting variables from the URL

 var url_variable = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        var p=a[i].split('=', 2);
        if (p.length == 1)
            b[p[0]] = "";
        else
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));

The section of my original script where I utilized these variables looks like this:

{
    photo_set: url_variable["album"],
    tag: url_variable["tag"]
},

This means that if I wanted to display an album of my top abstract photos, I could create a URL like so: myphotosite.com/page.html?album=abstract&tag=best

It works perfectly!

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

Hide specific content while displaying a certain element

Creating three buttons, each of which hides all content divs and displays a specific one when clicked. For instance, clicking the second button will only show the content from the second div. function toggleContent(id) { var elements = document.getEl ...

Is it essential to transmit the information in $.ajax as JSON format?

My current $.ajax request sends data in a serialize() format and receives a json array in response. This setup functions flawlessly on Chrome developer tools and Firefox's firebug. However, I am questioning whether it is necessary for me to send the u ...

Having trouble with VueJS Router-link not redirecting to the correct view?

I am facing an issue with the router link. When I use it in a view, it works perfectly fine as I have a clickable link. However, when I include a router link in a component nested within a view, the router link stops working - all I want is to link to the ...

Guide to extracting data from a customized JSON file using PHP

My JSON data looks like this: { "A": {"id":"1","checked":false}, "B": {"id":"2","checked":true}, "C": {"id":"3","checked":true} } I am interested in extracting the id and checked values. The specific values under A,B,C are unknown to me. $j ...

jQuery/JavaScript - storing a pointer to an array instead of its values

I am attempting to consolidate several similar functions into a single function, which requires making calls to different arrays and variables. However, I seem to be missing something in my implementation. Here is the code snippet: var initialPreloadArray ...

Incorporating JavaScript Variables into MySQL Database with AJAX: A Step-By-Step

Looking to implement the solution provided in this query about adding records into a database using php/ajax/mysql: Best way to add records into DB using php/ajax/mysql? This is my current code: JavaScript function FromFlash(m1, m2, m3, m4){ var po ...

Enhancing HTML "range" element with mouse scroll functionality for incrementing values in step increments

I'm working on developing a scroll feature that operates independently from the main window's scrolling function. I aim to trigger specific events in the primary window based on interactions with this separate scrollbar. The only solution I coul ...

Explore the power of accessing XML data using JavaScript

Currently, I am dealing with an XML file and attempting to extract data from it. The structure of the XML file is as follows: <doc> <str name="name">Rocky</str> <str name="Last_name">balboa</str> <str name="age ...

Interacting with distant servers within XD plugins

Currently in the process of developing an XD plugin, with a goal of fetching images from a remote server. Is this achievable and are there specific APIs that can facilitate this task? ...

Writable Input-Buttons in Bootstrap now enabled

This is the appearance of my Button: <input class="btn btn-outline-primary" id="dashboard" value="Zurück" onclick="doStuff();"> It's just your typical Bootstrap styling. However, things take a strange turn when I click the button and change i ...

Mobile issue: unable to scroll to the top of the page

Despite my efforts in searching and attempting various solutions from SO, I have still been unsuccessful. I have explored options like the iscroll library and setting timeouts, but to no avail. My objective is to enable scrolling to the top of the window/ ...

Encountering an issue with file uploading in Firebase: Error message indicates that AppCheck is being utilized before activation

I am facing an issue while trying to upload a file to my firebase account. Whenever I attempt this, I encounter the following error message: Uncaught (in promise) FirebaseError: AppCheck: AppCheck is being used before activate() is called for FirebaseApp ...

Creating a search query in Alfresco Full Text Search to locate a JSON text file

I need to perform a precise search in a JSON text file using Alfresco Share's Full Text Search functionality. For instance, assume the JSON-formatted text below is present in the file - can I execute a query to find an exact match for the fields test, ...

Generating a JSON Array by aggregating data from a loop with the help of the Spring Boot framework

Recently, I successfully implemented a code to import data from a .pcap file. The code works flawlessly as it reads the cap files and displays the results in the console. The implementation of this code can be seen below: @SpringBootApplication public cl ...

Python library gspread is causing all the data in a data table to be consolidated into a single cell in my Google Sheets rather than being dispersed

Looking to update a Google Sheets document by replacing the content of its first sheet with my own data table, I tried using the gspread module without much success. When running the line client.open("GoogleSheetName").sheet1.update('A1:R181',Me ...

Components with no specific branding in Vue

Creating a quiz in Vue.js with various question types: Select one Select multiple Select image Match The challenge lies in the mixing of question types within the same quiz, leading to the use of different components (<x-select-one-question>, < ...

Looping through a JSON object within the server environment

If I have a basic model set up like this: public class User { public string ID { get; set; } public string Name { get; set; } public string Age { get; set; } } and let's say I receive a JSON object structured as follows: var users = { ...

The jQuery .ajax() function encountered a 405 error stating "Method Not Allowed" when attempting a cross

Despite searching extensively on SO, I am unable to pinpoint the issue in my code. To avoid using JSONP, I am implementing CORS. I understand that this is a preflighted request and believe I have included the correct headers. The problem lies in the web ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

The Jquery widget for autocompletion - "select( event, ui )"

I've implemented jquery for my autocomplete search bar. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8. ...