Jump to content

need help with this javascript ajax

Nipplemilk909

hello

im having trouble with this project 

 

In this assignment we will be using AJAX to make requests to a free weather API called OpenWeatherMap. You will need to create a free account with OpenWeatherMap to obtain an API key in order to access their API. Once you create an account and are signed in your API key will be located under the API keys tab.

 

Create a file named ajax.js with the following implementation of a function named ajax. This file defines a function named ajax, which we can reuse within a Web application.

 

and that file i got here 

//ajax.js
function ajax(url, handler) {
    var req = new XMLHttpRequest();
    if (!req) {
        alert('Browser not supported.');
        return;
    }

    req.onreadystatechange = function() {        
        var resp;        
        if (this.readyState === XMLHttpRequest.DONE) {           
            if (this.status === 200) {               
                resp = this.responseText;            
                handler(resp);            
            } else {               
                handler('Ajax error, status: ' + this.status);           
            }       
        }    
    };
    req.open('GET', url);
  req.send();
}

Next create a file named index.html with the following contents. On the line where the apiKey var is being set, make sure to replace the value "APIKEY" with your actual API key you obtained from OpenWeatherMap.

 

and here is that index : for the api key i replace the key with no string elements just how it looks there not sure if i should put it into quotations. 

<!DOCTYPE html>
<html>
	<head>
		<title> <!!!!YAUZA!!!!></title>
		<link rel="stylesheet" href="style.css" />
	</head>
	<body onload = "showDate()">
		<div class = "header">
			<h1 id = "headline"> CSE DOM Javascript</h>
			<p> Miguel   </p>
			<button id = "btn"> Add New Item </button>
			<ul id = "list">
				<li>one</li>
				<li>two</li>
				<li>three</li>
				<li>four</li>
			</ul>
			
			<script src = "javatut1.js"> </script>	
		</div>
		
		<div id="container" />

            <script src="ajax.js"></script>
            <script src="parse-response.js"></script>
    
            <script>
                /* global ajax */
                /* global parseResponse */
                var container = document.getElementById('container');
                var url = "http://api.openweathermap.org/data/2.5/weather?q="; 
                var city = "San Bernardino"; 
                var apiKey = 5b9dc5cd; // Replace "APIKEY" with your own API key; otherwise, your HTTP request will not work 
                url += city + "&appid=" + apiKey; 
                ajax(url, function(resp) {     
                resp = parseResponse(resp);  
                container.appendChild(document.createTextNode(resp)); 
                    }); 
            </script>
		
	</body>
</html>

Start the Apache Web server with apache2 -k start command. Get your url with echo $C9_HOSTNAME and paste it in a new tab in your web browser. Click on your A10 folder and you should see your Web page displaying a JSON string containing weather data for San Bernardino. 

 

The next step is to parse the JSON string into an object so that we can pull out the data that we are interested in. For simplicity, in this exercises we are only going to use the data pertaining to the city, country, temperature, and weather condition. 

Create a file called parse-response.js with the following content: 

 

here is the parese file 

 function parseResponse(responseText) { 
     var response = JSON.parse(responseText); 
     var condition = response.weather[0].main; 
     var city = response.name; 
     var country = response.sys.country; 
     var degK =  response.main.temp; //temperature data is in Kelvin 
     var degF =  1.8*(degK - 273) + 32; //Converting Kelvin to Fahrenheit.  
     degF = Math.floor(degF); //removing decimals 
     var weatherBox = document.getElementById("weather");  
     response = city + ", " + country + " " + degF + "\u{00B0}" +" F " + condition; 
     return response;  
}

I dont know why this next step wants it bold 

Add the following lines in bold to index.html and save your work.

<div id="container" />

<script src="ajax.js"></script>
<script src="parse-response.js"></script>

<script>
/* global ajax */
/* global parseResponse */
var container = document.getElementById('container');
var url = "http://api.openweathermap.org/data/2.5/weather?q="; 
var city = "San Bernardino"; 
var apiKey = "APIKEY"; // Replace "APIKEY" with your own API key; otherwise, your HTTP request will not work 
url += city + "&appid=" + apiKey; 
ajax(url, function(resp) {     
resp = parseResponse(resp);  
container.appendChild(document.createTextNode(resp)); 
}); 
</script>

 

Refresh your Web page and you should see the city, country, temperature, and weather condition displayed. 
 

Modify index.html to contain a text box for the user to type in a city and a submit button. When the user types a city into the textbox and then clicks the submit button, the page should update with new weather information for that city. The old city weather information should be completely replaced with the new city weather information(I should not see multiple cities being displayed each time I click submit). You'll need to define a function that handles click events generated by the submit button. To intercept the click event, you need to add a onclick attribute to the submit button and set it to the click event handler function. Your event handler function should contain the code that calls the ajax function and should use the city that the user entered instead of "San Bernardino" for the OpenWeatherMap API url.  

 

Link to comment
Share on other sites

Link to post
Share on other sites

What's your problem?

I don't know ajax, but the person that does is going to ask the same question. 

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, fpo said:

What's your problem?

I don't know ajax, but the person that does is going to ask the same question. 

its not compiling the weather app once ive replace the api key 

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Nipplemilk909 said:

its not compiling the weather app once ive replace the api key 

Did you include the weather API properly, and put the files in the project folder properly?

 

If it's anything like Java, you can add API by taking "Jars" and telling the compiler you're using them, and then you may have to include them by typing include in the text file. 

Link to comment
Share on other sites

Link to post
Share on other sites

Looks like your API key should be a string. It's not, which is probably why it doesn't work. 

Link to comment
Share on other sites

Link to post
Share on other sites

12 hours ago, elpiop said:

Looks like your API key should be a string. It's not, which is probably why it doesn't work. 

api keys are suppose to be submitted as strings?

 

Link to comment
Share on other sites

Link to post
Share on other sites

14 hours ago, Nipplemilk909 said:

api keys are suppose to be submitted as strings?

 

   

            var apiKey = "APIKEY"; // Replace "APIKEY" with your own API key; otherwise, your HTTP request will not work 

Well what you posted seems to imply that
 

Link to comment
Share on other sites

Link to post
Share on other sites

4 hours ago, elpiop said:

   


            var apiKey = "APIKEY"; // Replace "APIKEY" with your own API key; otherwise, your HTTP request will not work 

Well what you posted seems to imply that
 

right but its stating to replace "APIKEY"  so even the quotes as well i assume which would not make it a string ?

Link to comment
Share on other sites

Link to post
Share on other sites

 

On 17/11/2017 at 3:01 AM, Nipplemilk909 said:

api keys are suppose to be submitted as strings?

 

yes. Other then it not finding the stylesheet, javatut1.js and showDate <- this function isn't defined anywhere your code works just find. I added a console.log() to ajax to print out what it gets form the API. It is a good way to debug

 

Open the html and press ctrl + i and put any errors you're getting here. 

On 16/11/2017 at 6:46 AM, Nipplemilk909 said:

Modify index.html to contain a text box for the user to type in a city and a submit button. When the user types a city into the textbox and then clicks the submit button, the page should update with new weather information for that city. The old city weather information should be completely replaced with the new city weather information(I should not see multiple cities being displayed each time I click submit). You'll need to define a function that handles click events generated by the submit button. To intercept the click event, you need to add a onclick attribute to the submit button and set it to the click event handler function. Your event handler function should contain the code that calls the ajax function and should use the city that the user entered instead of "San Bernardino" for the OpenWeatherMap API url.  

 

I assume you want help with this? this is simple.

 

Create an HTML input, create a function, when you press a button get the value of the input and pass that to ajax.

 

I assume the answer is what you're after. This is how I would do it. It returns the error to user such as city note found and so on. It uses promises because ew call backs.

 

index.html

<!DOCTYPE html>
<html>
	<head>
		<title>Weather</title>
	</head>
	<body onload = "showDate()">
		<input id="q" placeholder="Search">
		<button id="search" >Search</button>
		<div id="weather"></div>

		<script src="script.js"></script>
	</body>
	<script>
		var container = document.getElementById('weather');
		//event listener 
		var el = document.getElementById("search");
		el.addEventListener("click", async function(){
			let q = document.getElementById('q').value;
			console.log(q)
			let url = "http://api.openweathermap.org/data/2.5/weather?q=" + q + "&appid=" + apiKey;
			try {
				let response = await ajax(url)
				console.log(response)
				let data = await parseResponse(response)
				console.log(data)
				container.innerHTML = data
			} catch (error) {
				console.log(error)
				container.innerHTML = error
			}
			
		});
	</script>
</html>

script.js

var apiKey = "8f9d4ff90acddd2804bfef9f2b2c5fc9"; // Replace "APIKEY" with your own API key;

function ajax(url) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.onload = () => resolve(xhr.responseText);
      xhr.onerror = () => reject(xhr.statusText);
      xhr.send();
    });
}

function parseResponse(responseText) {
    return new Promise((resolve, reject) => {
        try {
            var response = JSON.parse(responseText); 
            var condition = response.weather[0].main; 
            var city = response.name; 
            var country = response.sys.country; 
            var degK =  response.main.temp; //temperature data is in Kelvin 
            var degF =  1.8*(degK - 273) + 32; //Converting Kelvin to Fahrenheit.  
            degF = Math.floor(degF); //removing decimals 
            var weatherBox = document.getElementById("weather");  
            response = city + ", " + country + " " + degF + "\u{00B0}" +" F " + condition; 
            resolve(response);
        } catch (error) {
            var error = JSON.parse(responseText);
            reject(error.message)
        }
         
    });
}

 

 

 

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×