Connecting a JavaScript variable

Is it possible to include a JavaScript variable in a link? I've tried the code below but it just shows a blank page. The viewData.php file will contain PHP GET Variables used to retrieve data based on the period and type, which determine whether rental or sales amounts are being pulled. The period will be specified in the format yyyymm.

$(document).ready(function(){
init();
 });
 function init(){
 months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
 urls = ['http:/testServer/testPage/viewData.php?period=' + series.name + ''];

$.ajax({
url: 'readData.php'
}).done(function(data) {
    ar = data.split('###');
    for(var i=0;i<ar.length;i++){
        ar[i] = ar[i].split('##');
    }
    for(var i=0;i<ar[0].length;i++){
        text = ar[0][i].split(' ').join('');
        year = text.substring(0,4);
        month = parseInt(text.split(year).join(''));
        month = months[month-1];
        ar[0][i] = month +','+year;
        ar[1][i] = parseFloat(ar[1][i]);
        ar[2][i] = parseFloat(ar[2][i]);
    }
    count = 0;
    dates = [];
    dates.push(ar[0][0]);
    for(var i=1;i<ar[0].length;i++){
        count++;

            dates.push(ar[0][i]);


    }
    dates[dates.length-1] = ar[0][dates.length-1];
    createGraph(ar,dates);
}); 
 }
   function createGraph(ar,dates){

        $('#60MonthAmount').highcharts({

        chart: {
            type: "line"
                },

        title: {
            text: '60 Month Revenue by Location Chart'
        },
        subtitle: {
            text: ''
        },
        xAxis: {
            title: {
                text: 'Time Period'
            },
            labels: {
                formatter: function() {
                    return this.value; // clean, unformatted number for year
                }
            },
            categories: dates,
            minTickInterval: 6,
            showLastLabel: true,


        },
        yAxis: {
            title: {
                text: ''
            },
            min: 0,
            labels: {
                formatter: function() {
                    return this.value / 1000000 +' mil';
                }
            }
        },
        tooltip: {
            pointFormat: '{series.name} produced <b>${point.y:,.0f}</b><br/><p style="visibility: hidden;">_</p>'
        },
        plotOptions: {
        series: {
            cursor: 'pointer',
            point: {
                events: {
                    click: function() {
                        if(this.x>urls.length){
                            url = urls[0];
                        }else{
                            url = urls[this.x];
                        }
                        window.open(url, '_blank');
                    }
                }
            }
        }
        },
        series: [{
            name: 'Rentals',
            data: ar[1]
        }, {
            name: 'Sales',
            data: ar[2]
        }]
    });
}

Answer №1

Is there a way to include a JavaScript variable in a hyperlink?

I am unsure about the significance of series.name, but it is crucial to use encodeURIComponent on any URL parameters to ensure proper encoding and validity.

var url = 'http:/testServer/testPage/viewData.php?period=' + encodeURIComponent(series.name);

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

What is the best way to delete an added element once a DIV has been toggled with JQuery?

I'm facing an issue where I need to add an element to a DIV that has a toggle function. However, every time I click the toggle again after adding the element, the same element is appended once more, resulting in duplicate elements. Upon observation, ...

Why is it not possible to pass references when utilizing a self-invoking function?

I have been experimenting with the IIFE pattern for some of my modules lately and encountered a problem that has stumped me. In my current project, I need to pass a few global variables for usage. One of these is the global googletag variable which initial ...

Python automation with selenium - capturing webpage content

I am utilizing selenium to scrape multiple pages while refraining from using other frameworks such as scrapy due to the abundance of ajax action. My predicament lies in the fact that the content refreshes automatically nearly every second, especially finan ...

Delay the loading of JavaScript libraries and multiple functions that are only executed once the document is

After learning how to defer the loading of JS libraries and a document ready function from this post, I encountered a challenge. The code I currently have handles multiple document ready functions inserted by different modules, not on every page. echo&ap ...

Next.js | Error: Attempting to access a property of an undefined value (property name: 'secret')

I encountered an issue while trying to authenticate the API routes in next.js. The page level authentication is working properly, but when attempting to fetch the session in the API routes, I am facing an error. Error - TypeError: Cannot read properties of ...

Discover the method for inserting a title attribute value into a span element

Utilizing AngularJS to retrieve and display data within a span element. I am now aiming to utilize this value as the title for another span element. The current code being used is shown below: <span style="display: inline-block; width: 160px">{{acti ...

I encountered an issue when sending a PATCH request via Hoppscotch where the request body content was returned as 'undefined', although the username and ID were successfully

const express = require("express"); const app = express(); const path = require("path"); let port = 8080; const { v4: uuidv4 } = require('uuid'); app.use(express.urlencoded({extended: true})); app.set("views engine", ...

Passing a parameter to an AngularJS directive, which triggers the opening of an ngDialog, and subsequently updating the value to reflect changes in the root scope

Struggling with a persistent issue here; Essentially, I have a directive that triggers an ngDialog to open. This directive should be able to receive a variable from the root scope. The directive contains a click event that opens an ngDialog which then use ...

Lack of y data in the Highcharts

I am facing an issue with retrieving yAxis data in Highcharts. You can view the fiddle at https://jsfiddle.net/LLExL/6496/. I have loaded Highcharts using the code below. $(function () { $('#RankingReportsHistory').highcharts( ...

What is the best way to position a rectangle on top of a div that has been rendered using

I recently started using a waveform display/play library known as wavesurfer. Within the code snippet below, I have integrated two wavesurfer objects that are displayed and positioned inside div elements of type "container". My goal is to position my own ...

Preventing autocomplete from filling in empty password fields (React.js)

Once the browser autocompletes my login form, I notice that the password input's value is initially empty. However, when I click on the password field, suddenly the value appears. Additionally, there are several inexplicable events being triggered by ...

Solving templateUrl resolution of directives in Angular with RequireJS

Currently, I am using AngularJS and RequireJS in my single-page application (SPA). To organize imports efficiently, I rely on RequireJS. With RequireJS, I can utilize features like baseUrl to resolve import paths seamlessly. Now, I wish to apply the same r ...

Is there a way to trigger Material-UI SpeedDialAction onClick events only when the SpeedDial is open and clicked, not when it is hovered over?

After making a modification to material-ui's <SpeedDial> component by removing the onMouseEnter={handleOpen} prop, I noticed that the onClick event within the <SpeedDialAction> component no longer triggers when clicking on a menu item. It ...

Click the button on your mobile device to open the already installed Android app

After creating a small Android app using jQuery Mobile, I incorporated a button to open another native Android app. Is it feasible for the jQuery Mobile app button to load/open an already installed and functioning native Android app upon click? I would gr ...

Difficulty retrieving information using AngularJS service post selection of item

Currently, I am working on a project involving an AngularJS application. While using the service testPanelService, I encountered a problem where selecting an item from a list correctly logs the details of the selected item. However, when attempting to fetc ...

Numerous points highlighted on the map

As I develop my application, I am working on setting up an event to automatically load data from a CSV excel file for display. My goal is to extract information from the Excel CSV file and use it to populate locations on a Google Map within my application ...

Incorporate geographical data from a JSON file into my Google Maps application

Hey there, I'm a newbie on this forum and could really use your expertise. I've put together an html5 page with Google maps using the API key from Google (My code is shown below), it's working fine with a central marker in place and loads pe ...

Implement a logging system to track and record data from both incoming requests and outgoing responses on a server powered by Express and Node.js

Is there a way for my server to log the response and request data when posting to another server? Thank you. const request = require('request'); postToIotPlatform = function postToIotPlatform(req, res, next) { var formData = JSON.stringify( ...

What could be the issue with this particular Ajax script?

I am facing an issue with this JavaScript code - it runs smoothly in Chrome and IE, but encounters a problem in Firefox. I need assistance in identifying the issue. Can anyone help? <script> function checkGurantee() { var gurantee = document.get ...

Begin a new countdown timer upon clicking the next button

Currently, I am developing a bid auction website and I have implemented a countdown timer script. The timer works perfectly on the initial window load. However, when I click on the restart button, it fails to reset the countdown timer to a new value. < ...