Tips for sending and retrieving an array of strings as a URL parameter and accessing query parameters in JavaScript

Hey there! I came across a URL like this: http:example.com/index.html?hideuielements=["Bookmark","Favourite"]

I'm curious if this is a valid query parameter that can be passed to a URL, and if so, how can we read it in JavaScript?

I'm hoping to use something like query.hideuielements to get values like ["Bookmark", "Favorite"] in my JavaScript file. Any tips or suggestions would be greatly appreciated!

Answer №1

If you need to pass an array, you can easily append it to the URL. In this example, I am concatenating it with the location.href in the code snippet below.

location.href += '?view_id=home;mode=embed;hideUIElements=[%22Bookmark%22,%22Filter%22,%22Favourite%22];'

To retrieve the array, you can utilize the following code if there is only one query (hideuielements) present. Otherwise, you will need to parse multiple queries by splitting the location.search using the & operator. The code provided below works correctly for a single query.

var query={};
location.href.split("?")[1].split(";").forEach(each=>{
    if(each.split("=")[0] === "hideUIElements") {
        query[each.split("=")[0]]=JSON.parse(decodeURIComponent(each.split("=")[1]));
    }
})

console.log(query)

Please review and confirm if this meets your requirements.

Answer №2

To retrieve data from a URL, using URL parameters and then capturing them with a server-side language like php is recommended. For instance:

www.my_site.com?hide=true&ui1=Bookmarks&ui2=Favourite

The PHP code to extract the information from the URL would look something like this:

<?php
$hide = $_GET["hide"];
$ui_array = array($_GET["ui1"], $_GET["ui2"]);
#$ui_array will hold the values "Bookmarks" and "Favourite"

#Then comes the JavaScript part
echo "<script>
if(" . $hide . " == true){
    //Perform actions with $ui_array
    something.hideuielements(" . $ui_array . ");
}
</script>";
?>

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

Utilize Uint8Array within a JavaScript ArrayBuffer

After generating a javascript ArrayBuffer from a FileReader ReadAsArrayBuffer method on a jpeg file, I am attempting to access the UInt32 array of the buffer and send it to a WCF service for insertion into a server database. I came across an example on St ...

What is the best way to compare the position-x of two components that are aligned on the same line?

Check out this code snippet: <input id="homebutton" type="image" style="display:inline" src="home.png" name="saveform" class="btTxt submit ml-3" onclick="location.href='home.html&apos ...

Tips for displaying the html content saved in the database onto an ejs webpage

This task seems simple, but I'm struggling to solve it. In my Node.js/Express webapp, I have the Quill.js editor installed. It stores my description in MySQL DB like this: <p><strong>This is the quill data. How are we doing dev?</stron ...

Loading Bootstrap accordion content with AJAX only when clicked

Is there a way to load ajax content into an accordion only when it is active? This could help prevent unnecessary data loading. It would be helpful to have a spinner displayed while the content is loading. I've searched online but haven't found a ...

Top method for verifying input during keyup or blur events

When it comes to validating user inputs, I often find myself wondering about the best approach to take. In this case, I have created a regex for numbers with decimal points. .ts part checkIsNumber(event) { console.log('event', event.target. ...

Retrieve elements with a customized attribute from an array in JavaScript

In my JavaScript code, I have added objects to an array, each with a new property called "Type". Now, I need to extract the objects from the array that have this "Type" property and put them into a new array. var arr = [ {ID: 1, Name: "Name1"}, {ID: 2, Nam ...

Using absolute positioning on elements can result in the page zooming out

While this answer may seem obvious, I have been unable to find any similar solutions online. The problem lies with my responsive navbar, which functions perfectly on larger screens. However, on mobile devices, the entire website appears zoomed out like thi ...

Save the uploaded file in Express to a custom directory on the system, avoiding the project's public folder

I have successfully integrated React on the front end to upload a file and receive it in Express.js. However, when storing the file in Express, it is currently being saved in the public folder. If I need to save the files in a non-public folder located at ...

Diving into Redux brings up the question of whether to use a generic reducer or a

When working with Redux, what is the preferred approach: Creating entity-specific reducers or utilizing a generic reducer based on strict action keying conventions? The former can result in more boilerplate code but offers loose coupling and greater flexib ...

Issue with jQuery AJAX error callback not triggering upon encountering an error

I'm currently facing an issue with implementing the management of an HTTP 413: Request entity too large error from my server. I've made the following attempt to address it: $.ajax({ url: "submit.php", data: { "data": POSTData ...

Understanding the concept of closures in JavaScript is crucial for effective programming

The snippet of code shown below continuously outputs the number 10. How can I modify it to display the sequence: 0 1 2 3 4 5 6 7 8 9 Below is the code in question: function go() { var procedures = []; for (var i = 0; i < 10; i++) { pro ...

Understanding the process of reading long values within a JSON object using JSON.NET

Below is an example of a JSON object: "bookshelf": { "shelfId": 5752814017970176, "shelfName": "Novels", "description": null, "bookOrder": "[5720369633689600, 5631072867975168, 5765651641663488, ...

Having multiple upload forms on a single page with PHP, AJAX, and jQuery is not functioning as expected

I'm on the hunt for a jQuery-AJAX image uploader that supports multiple instances of the form on a single page. Do you have any recommendations? Here's my scenario: I have a front-end page where users can update their profiles. Upon loading the ...

What are the steps to turn off a service worker for subdomains?

I'm currently using a web application built with Angular that includes a service worker. Whenever I make PUT and GET requests to s3.amazonaws.com, the requests are always routed through the service worker. What steps should I take to configure my app ...

Loading external JSON and images located beyond the root directory

Currently, I am attempting to load a JSON file and a set of images from a directory located above my root directory. Although the code I have works, I believe there may be a more efficient way to achieve this. $.getJSON("http://localhost/folder1/folder2/f ...

Conflicting Issues between jQuery Toggle and Mouseup Function

I have a straightforward button that, when clicked, toggles a menu. If the menu is expanded/visible, I want it to be hidden when clicking anywhere on the page (except for the menu itself). var menuBtn = $(".btn-menu"), menuContainer = $(".menu"), menuChi ...

Incorporating props into every page through getInitialProps in Next.js

I am trying to ensure that the same props are loaded on all pages I navigate to. My approach involves using _app.js as shown below: export default function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> } MyApp.getInit ...

Is fnPageChange malfunctioning due to a delay issue in JavaScript? Possible sequence error?

I have encountered an unusual problem that seems to be affecting several websites I manage using datatables. Whenever I try to use the fnPageChange function, it does not work unless there is a setTimeout workaround like this; setTimeout(function() { oTab ...

How to Add a New npm Package to Your Current React Native Application

I encountered an issue while trying to integrate npmjs.com libraries as dependencies in my current react native application. The instructions suggested running npm install twit in the terminal. Following this, I executed the command in VScode with my appli ...

Determine the number of radio buttons selected in each group (At least 2 selections in total)

I am looking to validate 7 sets of Radio Buttons, ensuring that a minimum of 2 sets are selected. If not, an alert should be displayed. However, it's important to note that there are additional radio buttons on the page that are not part of this valid ...