Updating AJAX parameters for HighStocks

My highstocks chart fetches JSON data from Yahoo and data structure is in the format of "www.blahAAPLblah.com".

I am trying to dynamically change the value of AAPL in the URL to other company ticker symbols so that I can fetch the data and display it on my chart. When manually changing the string to GOOG, it works fine. Additionally, setting var ticker = 'GOOG' and modifying the URL to "www.blah" + ticker + "blah.com" also produces the desired result.

However, when attempting to use a user input box with

var ticker = document.getElementById('userInput').value;
, everything stops working.

Any suggestions to resolve this issue would be greatly appreciated.

Here is the current state of my code: http://jsfiddle.net/SgvQu/

UPDATE: I have tried implementing JSONP for the request but the chart still fails to load.


    var closePrices = new Array();
    var dateArray = new Array();
    var timeStampArray = new Array();
    var timeClose = new Array();

function jsonCallback(data, ticker) {
            console.log( data );

            // Storing closing prices in an array and converting to floats
            for(var i=0; i < data.query.results.quote.length; i++)
            {
                closePrices[i] = parseFloat( data.query.results.quote[i].Close );
            }

            // Displaying values in the closePrices array
            console.log( closePrices );

            // Storing dates in an array
            for(var i=0; i < data.query.results.quote.length; i++)
            {
                dateArray[i] = data.query.results.quote[i].date;
            }

            // Converting all dates into JS Timestamps
            for(var i=0; i < dateArray.length; i++)
            {
                timeStampArray[i] = new Date( dateArray[i] ).getTime();
            }


            for(var i=0; i<data.query.results.quote.length; i++)
            {
                   timeClose.push( [timeStampArray[i], closePrices[i]] );
            }

            timeClose = timeClose.reverse();
            console.log ( timeClose );

            // Displaying the dateArray
            console.log( dateArray );
            console.log( timeStampArray );

            // Creating the chart
        $('#container').highcharts('StockChart', {

            rangeSelector : {
                selected : 1
            },

            title : {
                text : ticker + ' Stock Price'
            },

            series : [{
                name : ticker,
                data: timeClose,
                tooltip: {
                    valueDecimals: 2
                }
            }]
        });
}

function createChart() {  

    var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22' + ticker +'%22%20and%20startDate%20%3D%20%222013-01-01%22%20and%20endDate%20%3D%20%222013-02-25%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?';
    //Ajax call retrieves the data from Yahoo! Finance API
    $.ajax( url, {
        dataType: "jsonp",  
        success: function(data, status){
            console.log(status);
            jsonCallback(data, ticker);
        },
        error: function( jqXHR, status, error ) {
            console.log( 'Error: ' + error );
        }
    });
}


//Function to get ticker symbol from input box.
function getTicker() {
        var ticker = document.getElementById('userInput').value;
        createChart(ticker);
    }

Answer №1

Big shoutout to Sebastian Bochan for guiding me towards JSONP. With his help, I finally got the chart working 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

How can I trigger HierarchicalDataSource.read() when the kendoDropDownList's change event is fired?

Currently, I am utilizing the treeview and HierarchicalDataSource features of KendoUI. Additionally, I have included a kendoDropDownList at the top of the page. Each time a user changes the value of the dropdown list, it triggers the 'change' eve ...

Using a JavaScript function to post the input value and then displaying it through PHP

I am striving to create an input field that will capture the value of what is typed and display it. The JavaScript function is designed to retrieve the value of the input box two seconds after the user stops typing and then post it. However, the issue lies ...

The Express server automatically shuts down following the completion of 5 GET requests

The functionality of this code is as expected, however, after the fifth GET request, it successfully executes the backend operation (storing data in the database) but does not log anything on the server and there are no frontend changes (ReactJS). const ex ...

What are the steps to implementing partial page functionality with the $http service in Angular?

Could someone assist me with executing an operation once a partial page has been successfully loaded using the $http service in Angular? The operation involves checking a checkbox based on the scope value. I have included the source code below: Here i ...

Having trouble with jQuery live clock freezing your browser?

I recently created a clock script and utilized setInterval to keep it running smoothly. However, I've encountered an issue where my browser freezes after a short period of time. Unfortunately, I'm unsure how to troubleshoot this problem on my own ...

Swap image using jQuery when clicked

Looking for help with a jQuery slide code that I have been working on. Here is the correct code snippet: <script type="text/javascript"> $(document).ready(function() { $(".slidingDiv").hide(); $('.secondarytitle'). ...

Guidance on implementing a Cypress assertion for a JavaScript object retrieved via ag-Grid

Seeking guidance as I navigate the world of UI automation and Cypress, specifically in setting up assertions on JavaScript objects returned by the cypress-ag-grid package Currently, my code is extracting data from ag-grid cy.get("#myGrid").getAg ...

What is the best way to append a JavaScript object to a JSON file on a new line

What changes should be made to this function in order to append each object in the file on a new line? exports.addWaypoint = function(id, type, param){ var dataIn = fs.readFileSync('./markers.json'); var obj = JSON.parse(dataI ...

Add data to form by clicking on the map using Mapbox

When using mapbox, I am able to insert a marker on map click and want to append those values in a form so that I can use my controller to store them. The marker is added and values are appended; however, https://i.sstatic.net/Tv1lk.jpg In the last value ...

Is it possible to integrate AngularJS with jQuery bootgrid?

Despite spending two full days delving into jQuery Bootgrid and AngularJS documentation, I am still struggling to implement angular directives on my dynamically generated grid. My setup involves AngularJS 1.6.6 and jQuery Bootgrid 1.3.1. The page itself i ...

Changing a string into an attribute within a nested JavaScript object

I need help accessing a string "key1.key2" as properties of an object. For instance: var obj = { key1 : {key2 : "value1", key3 : "value2"}}; var attr_string = "key1.key2"; The variable attr_string represents attributes in a nested object that are connect ...

Jest anticipated the mock function would have been invoked

Currently, I am running tests on a specific service. Here is the code snippet for the service: import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { ...

When invoked, a Javascript Object comes back empty

My code snippet: const channels = fauna.paginate(q.Match(q.Index("channels"), "true")) // Query FaunaDB database for channel list => create constant called users containing results const channelList = channels.each(function (page) { ...

Interaction when a button is clicked repeatedly 10 times on a webpage

Looking for assistance in creating a website feature where clicking a link ten times opens another webpage. Any help would be greatly appreciated. Thank you in advance! ...

Refresh the Document Object Model (DOM) and transmit the present time

I am having an issue with sending the actual current time when a button is clicked. Instead of getting the current time, I am receiving the time when the page initially loaded. This button is used to submit a form on Google Sheets using an API. This is th ...

Having trouble uploading a file to Node JS

After commenting out the app.use(fileUpload) line, I noticed that the breakpoint set on app.post is triggered from the browser. However, an error occurs stating Exception has occurred: TypeError: Cannot read property 'filetoupload' of undefined ...

Using NextJS to Load Fonts from a Database

I've implemented a feature in my NextJS and Tailwind CSS app that allows users to select a theme with different color schemes and font options. The fonts available are all from Google Fonts. However, I'm facing an issue with loading the selected ...

When a previous form field is filled, validate the next 3 form fields on keyup using jQuery

Upon form submission, if the formfield propBacklink has a value, the validation of fields X, Y, and Z must occur. These fields are always validated, regardless of their values, as they are readonly. An Ajax call will determine whether the validation is tru ...

MUI version 5 - Checkboxes are receiving a variety of unique classes

After recently upgrading from Mui v4 to v5, I've noticed a strange behavior with checkboxes. Upon inspecting the DOM differences between the two versions, it appears that some additional classes are now being applied in v5 and the extra span with the ...

Using jQuery to send legitimate JSON data in the request payload

After checking the jQuery Ajax documentation, it seems that by default, data gets serialized as a query string when sending requests. However, I learned that setting processData:false should allow me to send actual JSON in the request body. The problem is, ...