Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this:

<body ng-controller="DashboardDisplay" onload="submit()">
    <div class="container-fluid" >

        {{scope.arr}}
    </div>
</body>
<script>

var myApp = angular.module('myApp',[]);
myApp.controller('DashboardDisplay', ['$scope','$http',function($scope,$http) {

    $scope.submit = function(){
        var jsonOb = {"A":"B"};
        $http.post(URL,jsonOb).
        success(function(response) {
            console.log('got it' + response);
            $scope.arr=response;
        })
    }
    }]);

At the moment, I have hardcoded the value of the variable jsonOb. However, for different pages, only the value of this variable changes. For example, on www.xyz.com/page1.html, jsonOb={"A":"B"}, while on www.xyz.com/page2.html, jsonOb={"1":"2"}. The rest of the HTML code remains identical. This redundancy bothers me as I am essentially using separate HTML pages just to set the value of one variable.

I am looking for a way to dynamically change the value of the variable based on the URL being queried. How can I achieve this?

Note: I am hosting the content using an express server.

Answer №1

If you want to efficiently store your JSON data, consider saving them in individual .json files and then accessing them based on the hash property of the window.location object: For instance, let's say you have file1.json, file2.json, and so on.

var hash = window.location.hash;
var jsonPage;
if (hash.length) {
     jsonPage = hash.split('#')[1]
     }
else {
     jsonPage = 1;
     }

You can now load your JSON pages by referencing the value after the HTML file name like your_url/page.html#2:

var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest();
else if (window.ActiveXObject) xhr = new window.ActiveXObject("Msxml2.XMLHTTP");
if (!xhr){
    checkOldBro(true); 
    return;
    }
xhr.onreadystatechange = function(){
    if (xhr.readyState == 4 && xhr.status == 200){
        var jsonOb = JSON.parse(xhr.responseText);
        $scope.submit = function(){...your function}
        }
    };
xhr.open("GET", "file"+jsonPage+".json", true);
xhr.send();
})(this);

Additionally, you can monitor the hashchange event, which allows for page updates without refreshing.

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

Struggling to grab the URL parameters using ExpressJS

Currently, I am attempting to extract the parameter values from the callback URL received from the Fitbit API. The callback URL structure is shown below, http://localhost:9000/callback#access_token=********&user_id=*******&scope=sleep+settings+nu ...

adjusting array based on screen size fluctuations

Imagine having two arrays of images named landscape_images[] and portrait_images[]. One is for the landscape view and the other for the portrait view. When the screen width is in landscape mode, the wide resolution images will be displayed on the body. C ...

Modifying the appearance of scoped child components in Vue: A step-by-step guide

I am currently using vant ui components in my Vue project, such as buttons. I would like to make some minor style adjustments, like changing the color and border, but I am unsure how to do it. Can anybody please assist me in solving this issue? Thank you i ...

Utilizing ReactDOMServer's renderToString method along with properties

Utilizing SSR serves the purpose of concealing location data from the client. My goal is to retrieve the location object from the findLocation function and transmit it to the react app. However, my attempts to pass it as a prop have been unsuccessful, lead ...

The POST request is coming back as null, even though it includes both the name and

Having issues with a login PHP code where the post method is returning an empty string. Here is my HTML code: <form action="iniSesion.php" method="post"> <div class="form-group"> <input type="email" name="email_" class ...

What is the best way to use PHP in order to retrieve the element containing the visit ID from the specific row within an HTML table?

I am working on a project that involves populating an HTML table with data from a database. The table includes an approval button for administrators to approve visits and change their status to APPROVED. I am trying to figure out how to select the element ...

Looking for a way to locate any elements in jQuery that do not contain a certain CSS class?

I am looking to target all form elements that do not contain a specific CSS class. For example: <form> <div> <input type="text" class="good"/> <input type="text" class="good"/> <input type="text" class="bad"/> ...

Display an image overlay upon hovering over a div

I've developed an add-on for Elementor that includes a card with the following HTML markup: <div class="card"> <div class="header"> <img src="img.jpg"> < ...

Is there a way to adjust the border color of my <select> element without disrupting the existing bootstrap CSS styling?

In my Bootstrap (v4.5.3) form, the select options appear differently in Firefox as shown in the image below: https://i.sstatic.net/3suke.png Upon form submission, I have JavaScript code for validation which checks if an option other than "-- Select an Op ...

What is the reason for the crossed out background image CSS in the Datatables header within Zurb Foundation 5.5.3?

I am facing an issue with displaying images in a wide Datatables header. The design is based on the Zurb Foundation 5.5.3 framework. Does anyone know why this CSS code is being strikethrough in the image below? (you can view it at which uses Zurb Founda ...

Is it possible to pass one handlebars template into another handlebars template and render them both simultaneously?

I have a unique system for managing articles on my website. Each article is stored as its own HBS file, which I then render using Express. While injecting HTML into a Handlebars template is simple, I wonder if it's possible to inject Handlebars code d ...

What is the best way to structure and send messages over TCP in node.js?

Currently, I am working on a project that involves sending a JSON string to multiple TCP clients from a node.js TCP server. To successfully handle the incoming messages on the client end, I need to implement message framing. One approach I am considering ...

How can I insert PHP code within the style attribute of a div tag?

I tried implementing this code, but unfortunately it's not functioning properly. My goal is to take user-defined width and height inputs in PHP and use them to generate a shape. echo "<div style='width:<?php $sirina?>;height: <?php $v ...

Error: The parent selector "&" cannot be used in top-level selectors. $::webkit-input-placeholder

I am facing an issue while trying to run a legacy create-react-app that utilizes Sass. Initially, when I ran npm start, I encountered the error 'Cannot find module sass', which resembled the message found in this stack overflow post. To resolve t ...

Is there a way for me to identify which dependencies are relying on a specific package within my node_modules directory?

A new feature on Github now notifies users about security vulnerabilities in their package-lock.json. While I want to address these issues, it's challenging to identify which top-level package in my package.json needs an upgrade since most listed pack ...

How can I create a navigation bar with a search bar and a dropdown button using Material

Hello, excited to be posting my third question on SO after lurking for like 7 years. Currently, I am working with the Materialize framework and trying to design a search navigation bar with a vertical dropdown on the right side. This is how my code looks: ...

Date selection feature in Material UI causing application malfunction when using defaultValue attribute with Typescript

Recently, I discovered the amazing functionality of the Material UI library and decided to try out their date pickers. Everything seemed fine at first, but now I'm facing an issue that has left me puzzled. Below is a snippet of my code (which closely ...

What seems to be the issue with this basic Node.js function not functioning properly?

I'm attempting to utilize a function that returns a boolean answer and then verifying it using if-else statements. function checkDNS(domain, tld) { var dns = require('dns'); dns.lookup(domain+'.'+tld, function (err, addres ...

Unable to find the import "@mui/x-charts/PieChart" in the file "src/components/Pie/Pie.jsx". Could the file be missing or spelled incorrectly?

I utilized the PieChart component in my pie.jsx file pie.jsx import { PieChart } from '@mui/x-charts/PieChart'; const Pie = () => { return ( <div> <PieChart series={[ { data: [ ...

Adjust Font Size inside Circular Shape using CSS/jQuery

I have been searching for different libraries that can resize text based on the size of a container. However, my container is circular and I am facing difficulty in preventing the text from overflowing beyond the border. Below you will find a Fiddle conta ...