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

AngularJS: Utilizing angular-filter for grouping by two columns

I may come across as a bit confusing, so please allow me to clarify. Note: An operational piece of code (POC) has been included with this post. I have an array of objects with 3 properties: name name team team_rank $scope.players = [ {name: & ...

Ways to adjust the size of div and its elements to fit the window dimensions

When resizing the window, the banner image shrinks while the header and header items remain the same size. However, there is an issue when the header takes up around 30% of the screen in phone view. Here is the CSS code I am using: .headerdiv{ width: ...

Troubleshooting overlap problem between Skrollr and SlickNav

I successfully implemented Skrollr to fix images, similar to this example: Additionally, I am utilizing Slicknav for the menu functionality. However, I encountered an issue where the menu opens behind the fixed "parallax" image. Despite trying various ap ...

The issue of Rails time lagging by a day persists upon deployment on my server

When a user clicks on a day in my calendar, I pass a JavaScript time variable to my Rails controller using Ajax. Everything works perfectly when I test it locally, but once deployed on the server, the date appears to be one day behind the actual day click ...

Efficiently Parse JSON Data with Variable Root Name

Currently, I have successful codes that can de-serialize a JSON message. The JSON message contains a root name of "response", and the Response class has been annotated accordingly to reflect this. However, in practice, the JSON message may originate from ...

I'm encountering a "confirm" error within the data table. Any suggestions on how to resolve this issue?

When I try to use two datatables columns in confirm, an error occurs when the text 'do you want cancel?' is displayed. The issue seems to be with the text itself and not the code. How should we go about fixing this problem? This is my current cod ...

Challenges with loading content on the initial page load using the HTML5

Upon page load, I wanted to save the initial page information so that I could access it when navigating back from subsequent pages. (Initial Page -> Page2 -> Initial Page) After some trial and error, I ended up storing a global variable named first ...

What is the most efficient method for transferring session data from a Client component to a server component in NEXT.js version 13 and beyond?

Currently, I am working on a web application that requires passing session?.user?.email from the useSession() function in next-auth/react to a server-side component. This server-side component will then execute a fetch request to /api/users/email/ to deter ...

Understanding how to extract data from a nested JSON response in ASP.NET MVC

I retrieved data successfully from a simple json using this link and displayed it on the view with the code below. SpeciesController.cs using diversity.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using ...

Combining two objects retrieved using ngResource in AngularJS

Seeking guidance on merging two objects retrieved using ngressource. Every 5 seconds, I invoke my service to fetch a message and aim to append the new message with the older ones. The JSON message I receive: [ {"age": 0,"id": "my first tweet","name": "H ...

Express server experiencing a conflict with authentication sessions

Currently testing out a library found on this link and encountering a frustrating issue related to potential conflicts in cookie or header authentication. Upon logging into one account, everything runs smoothly. However, attempting to log into a different ...

Incorporate JavaScript to include a new class and attribute

Apologies for any language barriers.. I grasp that it involves using addClass and removeClass, but I am uncertain about how to write the terms. I need to ensure that if the screen resolution is less than 768 pixels, then the attributes id="dLabel" type="b ...

Listen up, Javascript keyboard input recorder

I am aiming for the search bar to pop up when you type. The code below is functioning, but I am facing an issue where the search bar pops up even when typing in a different input field, such as the comment input. Is it feasible for the search bar not to ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

Encountering a 'Cannot Get /' Error while attempting to reach the /about pathway

I attempted to create a new route for my educational website, and it works when the route is set as '/', but when I try to link to the 'about' page, it displays an error saying 'Cannot Get /about' Here is the code from app.js ...

What steps should I take to create a collapsible Bootstrap navbar?

I'm attempting to recreate the scrolling functionality seen here: It seems like they might be using a customized Bootstrap Navbar, so I've taken one from here: and tailored it to my needs. How can I achieve the effect where the navigation bar ...

JavaScript progress bar with extended duration, inspired by the success-oriented approach

Currently, I am in search of a unique solution or plugin that can replicate the same effect as Kickstarter's crowd fund long term progression bar. It seems like existing solutions only offer short term dynamic progress bars that indicate the percentag ...

ways to halt a noise once an animation is complete

I don't have much experience with coding in general, but somehow I've made it this far. Now I'm stuck on the final piece of the puzzle. This is related to a Twitch alert that I'm setting up through 'Stream Elements'. The iss ...

Using Mootools to call a class function from a bound CSS class may lead to an error stating that it is not a function

Utilizing Mootools 1.3.2 Here is the code snippet: var DNReportAbuse = new Class({ Extends: DNUserDialog, comment_id: null, container: null, initialize: function(classname) { var bindclass = $(document.body).getElements(classname); bindclass. ...

Saving vast array in MongoDB

I am currently working on a personal project that involves implementing a search feature. My setup includes using typeahead.js with a REST api created in expressJS and mongoDB. I could use some guidance on two particular challenges I am facing. While my ba ...