Chrome console displaying error: "API request open method is not a function."

Check out my weather app on Code Pen

Here's the code for my weather app (apologies if it's overwhelming):

var button=document.getElementById('submit');
var zipcode;
var lat;
var lng;
var weather;
var iconId;
var temp;

// Function to get the value entered by the user
button.addEventListener('click',getValue);
function getValue(event){
  event.preventDefault();
  zipcode=document.getElementById('zipcode').value;
  getCity();
}

// API request to Google Geocode 
function getCity(){
  var req=new XMLHttpRequest;
  req.onreadystatechange=function(){
    if(this.readyState==4&&this.status==200){
      var myData=JSON.parse(this.responseText);
      var myCity=myData.results[0].address_components[1].short_name;
      lat=myData.results[0].geometry.location.lat;
      lng=myData.results[0].geometry.location.lng;
      document.getElementById('lat').innerHTML=lat;
      document.getElementById('lng').innerHTML=lng;
      document.getElementById('city').innerHTML=myCity;
    }//if function end
  }//onreadystate function end
  req.open('GET','https://maps.googleapis.com/maps/api/geocode/json?address='+zipcode, true);
  req.send();
  getWeather();
}

// API request to Dark Sky Weather
function getWeather(){
  var request=XMLHttpRequest;
  request.onreadystatechange=function(){
    if(this.readyState==4&&this.status==200){
      var myWeather=JSON.parse(this.responseText);
      weather=myWeather.currently.summary;
      document.getElementById('weather').innerHTML=weather;
      console.log(myWeather);
    }//if ends
  }//onready end
  request.open('GET','https://api.darksky.net/forecast/6231bad7d2bf09aa53301a4227b7c1af/'+lat+','+lng, true);
  request.send();
}
<form>
  <input type=text placeholder='zipcode' id='zipcode'></input>
  <input type='submit' id='submit'></input>
</form>

<ol>
  <li>City Name: <span id='city'></span></li>
  <li>Latitude: <span id='lat'></span></li>
  <li>Longitude: <span id='lng'></span></li><br>
  
  <li>Temperature(F): <span id='temp'></span></li>
  <li>Icon: <span id='icon'></span></li>
  <li>Weather: <span id='weather'></span></li><br>
  <li>Wind(mph): <span id='wind'></span></li>
  <li>Sunrise: <span id='sunrise'></span></li> 
  <li>Sunset: <span id='sunset'></span></li>
</ol>

Explanation of my code: You input a zipcode and click 'submit', triggering an Event Listener that calls the 'getValue' function, storing the zipcode and then executing the 'getCity' function to convert the zipcode into the City Name, Latitude, and Longitude.

I initially placed the 'getWeather' function immediately after 'getCity' in the 'getValue' function definition, but I realized that wouldn't allow enough time to retrieve the Latitude and Longitude values from the first API. So, I placed it inside the 'getCity' function definition.

While the 'getCity' function successfully converts the zipcode into the City Name and Latitude/Longitude, the issue arises with the 'getWeather' function, which should provide weather conditions like 'Rainy'.

Error in Chrome Console: https://i.sstatic.net/rmEBR.png

EDIT: I added the 'new' keyword: var request= new XMLHttpRequest;. That was a simple typo. Here is the new error:

https://i.sstatic.net/q7FeS.png

EDIT 2: MAJOR DISCOVERY: I believe I know the issue. However, I'm unsure how to resolve it. It's a SCOPE problem! When I try console.log(lat+' and '+lng); in the 'getWeather' function, the console shows 'undefinedandundefined'. The only place I can access the Latitude and Longitude values is inside the 'getCity' function, where the first API converts the entered zipcode to Lat/Lng.

Answer №1

To start, ensure that the request object is properly created by instantiating it:

var request = new XMLHttpRequest();
.

Additionally, it is important to specify the request header. Use:

request.setRequestHeader('Access-Control-Allow-Origin', '*');

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

"Exploring the concepts of inheritance in Typescript

I'm seeking answers regarding inheritance in TypeScript/JavaScript. Below is my base class (express controller router): abstract class BaseCtrl { abstract model; // Get all getAll = (req, res) => { this.model.find({}, (err, docs) => ...

I'm wondering if there is a method for me to get only the count of input fields that have the class "Calctime" and are not empty when this function is executed

Currently, I am developing an airport application that aims to track the time it takes to travel between different airports. In this context, moving from one airport to another is referred to as a Sector, and the duration of time taken for this journey is ...

Troubleshooting an Ajax Error

Encountering an issue when trying to bind two components (checkbox and label) by using the "for" tag attribute for the label and the "id" tag attribute for the checkbox. An ajax debug error is thrown: "Cannot bind a listener for event "click" on element "v ...

What is the reason behind the failure of the cancel test?

I've created two test cases; one for testing the functionality of the Download button and the other for the Cancel button. However, I am encountering issues with the Cancel test failing consistently. Below is the code snippet where I'm attemptin ...

Trouble arises with MySQL query in PHP/jQuery setup

I am currently in the process of developing a user panel where users can change their first and last names. Everything seems to be working fine with the $ajax form handling, as I can use console.log(data) and see {fname: "Damian", lname: "Doman", id: "20" ...

Master the art of zeroing in on your drawing once it's complete

Please review the Demo and provide instructions on how to enhance the zoom function for Google Maps after the map is drawn. let map; let drawingManager; $(document).ready(function () { const latlng = new google.maps.LatLng(49.241943, -122.889318); ...

Can I inform the interpreter that my function in TypeScript specifically handles undefined and null values?

Consider a scenario where there is a method isEmpty that verifies if a value is empty, null, or undefined, and returns true accordingly. In TypeScript, this method may not effectively communicate to the interpreter, leading to a red underline in IDEs like ...

Ways to determine if a user is using a PC using JavaScript

I am developing a website using node.js that will also serve as the foundation for a mobile app. The idea is to have users access the website on their phones and use it like an app. But I want to implement a feature that detects when the site is being vi ...

Dissecting Distinct and Alphabetized Attributes in JSON/JavaScript

Below is a code snippet that retrieves and organizes a list of values from JSON data in alphanumeric order based on a specific key-value pair: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 &a ...

Disappearing Data in Chart.js When Window is Resized

I am utilizing the Chart.js library to present a line chart in a div that is enclosed within a <tr>. <tr class="item">...</tr> <tr class="item-details"> ... <div class="col-sm-6 col-xs-12 chart-pane"> <div clas ...

Unusual layout in Next.js editor (VS Code)

My chosen formatter is prettier, but I'm encountering an issue with the way it handles simple JSX functions. Initially, my code looks like this: function HomePage() { return; <div> <h1>Hello Next.js</h1> <p> Welcome ...

vue-form and vue-material are not compatible with each other

In my experience, using a Vue form on a regular HTML <input> element allows validation to work as expected. However, when I switch to using the <md-input> element, the validation no longer functions and an error message is displayed: Element ...

Paste the formatted text from clipboard into the body of a react mailto link

I have a requirement for users to easily send a table via email by copying and pasting it into the subject line. You can view a live demo of this feature on CodeSandbox: copy and paste rich text Below is the function that allows users to copy and paste ri ...

Changing an HTML table into an array using JavaScript

Is it possible to transform an HTML table into a JavaScript array? <table id="cartGrid"> <thead> <tr> <th>Item Description</th> <th>Qty</th> <th>Unit Price</th> ...

The dynamic import() syntax is not compatible with the target environment, preventing the use of external type 'module' in a script

I am currently facing an issue with my React app. The command npm start is working as expected, but when I try to run npm run build, it keeps failing. It's crucial for me to run npm run build in order to deploy the app on a website. I have already sp ...

JavaScript error caused by incorrect JSON parsing

Encountering Another Issue. Here's the Relevant Code: if(localStorage.getItem("temporaryArray")){ var temporaryArray = JSON.parse(localStorage.getItem("temporaryArray")); }else{ var temporaryArray = []; } Essentially, what this code snippet ...

Choose the date that is exactly 48 hours from now

I need to implement a date picker that shows today's date and the next 2 days in a select component. Can this be achieved using JavaScript and jQuery? While I came across a similar post on the topic, I specifically want it to work with a date picker: ...

Resolving the problem of degrading image quality in HTML Canvas

Recently, I came across an issue while trying to display graphics on an HTML page using canvas. The problem I encountered was that the canvas element was somehow reducing the quality of my images during rendering, especially after some time. Let me visual ...

Utilize Multer to upload images stored within an array of objects

I've been having difficulty figuring out how to extract the images from an array of objects structured like this: import mongoose from "mongoose"; const prodcutSchema = new mongoose.Schema( { title: { type: String, require ...

Thumbnail image preview fails to display after preloading an image in dropzonejs

Currently, I have a form where users can input their name and upload an image (logo). The client side language being used is AngularJS with dropzonejs as the image upload library. When the user clicks on the 'Edit' button, I want them to see a pr ...