Issue with Google Finance JSON response not functioning as expected in Chrome and Firefox browsers, yet appears to be working properly in

I am currently working on a JavaScript project that involves fetching STOCK data from the Google Finance API.

When I manually paste the link into my browser, I can successfully retrieve the JSON response:

// [ { "id": "22144" ,"t" : "AAPL" ,"e" : "NASDAQ" ,"l" : "108.51" ,"l_fix" : "108.51" ,"l_cur" : "108.51" ,"s": "0" ,"ltt":"10:48AM EDT" ,"lt" : "Aug 11, 10:48AM EDT" ,"lt_dts" : "2016-08-11T10:48:42Z" ,"c" : "+0.51" ,"c_fix" : "0.51" ,"cp" : "0.47" ,"cp_fix" : "0.47" ,"ccol" : "chg" ,"pcls_fix" : "108" } ]

But when I tried using the Yahoo Finance URL, I faced the same issue. Here is the URL I used:

Yahoo Finance URL

This is the JavaScript code snippet I am working with:

var url = "http://finance.google.com/finance/info?q=nasdaq:";

function getJSONReply() {
    var url_req = url.concat(arguments[0]);
    alert(url_req);
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText.length);
        }
    }
    xhr.open('GET', url_req, true);
    xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
    xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET');
    xhr.addEventListener("load", reqListener);
    xhr.send();
}

function reqListener() {
    var sub1 = this.responseText.substring(5,this.responseText.length);
    var sub2 = sub1.substring(0, sub1.length - 2);
    parse_JSON(sub2);
}

Note: Even when testing with a direct HTTP request string instead of using `var request`, the responseText remains empty.

xhr.open('GET', "http://ipinfo.io/json", true);

I'm unsure about what's causing the issue. In Chrome, the readyState is 1 and the status is 0, while in Internet Explorer, the readyState is 4 and the status is 200.*

Answer №1

There are several issues with the current process at hand. Firstly, there is an issue with trying to request data asynchronously using XMLHttpRequest without proper handling for it. Secondly, attempting to make a request may run into problems with the same-origin policy if executed on the client side within a browser. Furthermore, the returned JSON presents yet another problem with invalid formatting due to the presence of double forward slashes at the end, leading to parsing errors.

function getJSONReply(stock) {
  var url = "https://finance.google.com/finance/info?q=nasdaq:";
  var request = url.concat(stock);
  window.alert(request);
  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", reqListener);
  xhr.open('GET', request, true);
  xhr.send();
}

function reqListener() {
  console.log(this.responseText);
}

console.log(getJSONReply("AAPL"));

The resolution: Given that the Google Finance API has been discontinued, alternative APIs can be explored as suggested in another Stackoverflow thread.

Illustrative example:

function getJSONReply() {
  var url = "http://ipinfo.io/json";
  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", reqListener);
  xhr.open('GET', url, true);
  xhr.send();
}

function reqListener() {
  console.log(this.responseText);
}

getJSONReply();

Answer №2

Why not create a PHP script to handle data retrieval?

Your Ajax can call this page using arguments GET['qparams']. The data from Yahoo is poorly formatted, so I cleaned it up and now it should work properly.

$homepage = file_get_contents('http://finance.google.com/finance/info?q=nasdaq:'.GET['qparams']);
$homepage = str_replace(array("//"," ","\r","\n"), "", $homepage);
return $homepage;

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

The code line "npx create-react-app myapp" is not functioning as expected

When running the command 'npx create-react-app my-app', I encountered the following error message: Error: '"node"' is not recognized as an internal or external command, operable program or batch file. Before suggesting to cre ...

Utilizing AngularJS to implement checkbox selection within a table

I'm working on a method that will receive an Id from a table when a checkbox is checked and update the $scope.selected array in my Angular controller. If the checkbox is unchecked, it should remove the corresponding item from $scope.selected. Here&ap ...

Having difficulty showing custom events on angular full calendar

After pushing events loaded from the server, I am encountering an issue where they are not being displayed on the calendar. Interestingly, the events are in the correct format and can be seen when printed on the page, but for some reason, they do not show ...

Automatically generate numbering for an AngularJS ng-repeat list

I'm working on creating a student report list using Angularjs ng-repeat. My main issue is figuring out how to dynamically append numbering like an ordered-list to the generated list in the view. I am aiming for something similar to this: # | Name of ...

Tips on enclosing <li> elements within <ul> tags

Whenever I trigger the button within the .items class, it generates <li> elements in the following manner: <ul class="items"> <ul class="items"> <li>img1</li> ...

The function message.react in Discord.js is throwing an error

I have a Discord bot set up for reaction roles. I use IDs to cache the messages that need reactions and make sure the bot reacts with the appropriate emojis before further action. Here is my process for caching the messages: const guild = await client.guil ...

Rxjs: accessing the most recent value emitted by an observable

As shown in the demo and indicated by the title const { combineLatest, interval, of } = rxjs; const { first, last, sample, take, withLatestFrom } = rxjs.operators; const numbers = interval(1000); const takeFourNumbers = numbers.pipe(take(4)); takeFourNu ...

The JSON.stringify method may not accurately reflect the original object that was converted into a string

Working on a Connect Four app for my school project has been an interesting challenge. At the moment, I am grappling with JSON.stringify and trying to encode an object that holds a two-dimensional array of "hole" objects to eventually send it to the server ...

The combination of Array.pop and Array.indexOf is not functioning as expected

I'm having an issue with using Array.pop(Array.indexOf(value)). It seems to always delete the last element in the index, even if the value of that index is not what I intended. Can someone provide some guidance on how to resolve this? CheckBoxHandle ...

Passing resolved data from a parent state to a nested view in Angular UI Router

Currently, I am developing an Angular web application that will showcase various financial events for the user. These events are categorized under a single ID and grouped into different categories. Each group needs to have its own HTML <table> for di ...

Leverage the Frontend (Headless Commerce) to utilize the Admin API and retrieve products from Shopify

Attempting to retrieve products from Shopify using the Admin API (GraphQL) through my frontend. I utilized the following code: *I implemented "axios" on Quasar Framework, utilizing Headless Commerce const response = await this.$axios({ url: "https: ...

Removing a specific MySQL row using HTML in collaboration with Node.js

I've been working on a feature to allow users to delete specific rows from a table. Each row has a "Delete" link at the end, but when I click it, nothing happens. There are no errors displayed, and the console shows that 0 row(s) have been updated, ye ...

I am specifically looking to parse JSON data where the section is set to 2. However, when receiving a response, all JSON files are being

I have a response where I want to remove null cardviews. Specifically, I am trying to parse only JSON objects with the section == 2 condition. While this functionality works, my RecyclerView still displays null values beyond the array length. package com. ...

Using information retrieved from a JSON response

In my current project, I have set up a JavaScript object within a script tag. <script> searchdata = {"employees":[{"name":"john doe","sal": "10000"}]}; </script> I am utilizing the searchdata object in various functions as shown below: fu ...

Navigating through Dynamic URL Parameters with RouterLink in an Angular Application

Within my Angular 2 application, there exists a tab section where users can choose from a collection of separate yet contextually connected components. By clicking on one of these links, the corresponding component is loaded based on the routerLink definit ...

Capture the Promise Rejection

During my test with WebdriverIO, I consistently encounter an issue specifically with this line of code: await browser.waitForVisible('#tx-sent li', 15000) Intermittently, a Promise rejection error occurs: Error: Promise was rejected with the ...

Utilizing DOMPDF in conjunction with jQuery to generate PDF files

Apologies for any language errors in my writing. I am attempting to generate a PDF using a portion of HTML, utilizing jQuery, Ajax, and DomPDF. On the server side, I am using the following code: require_once './dompdf/autoload.inc.php'; if(!em ...

grab the content from a text editor and insert it into a div element

Currently, I am trying to extract text from my content editable div and place it in another div (similar to the one seen on stack overflow). However, I am encountering a frustrating issue. 1. My content div seems to be lagging behind. When I type in my ed ...

Utilizing Chrome Context Script plugin to monitor page changes: A step-by-step guide

Currently, I am in the process of creating a basic Chrome extension with the purpose of removing specific DOM elements from a particular website. In my manifest.json file: { "name": "example", "version": "1.0", "description": "example description" ...

Code in JavaScript often includes the use of variables to store and manipulate data

Do these blocks of JavaScript code serve the same purpose? // First Code Sample var first = prompt("Enter the first number:"); var second = prompt("Enter the second number:"); var sum = Number(first) + Number(second); alert(sum); // Second Code Sample ...