Make openweathermap api contents print in the console? [duplicate] - javascript

This question already has answers here:
How can I use Json Jquery in api.openweathermap to get weather information
(2 answers)
Closed 5 years ago.
According to the error I saw when I inspected the code, it has to be in this http format so I cannot change it. I'm trying to figure out how to console log this entire api document.
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.openweathermap.org/data/2.5/weather?zip=92407,us&appid=MY KEY GOES HERE YES I KNOW I HAVE TO ADD THE KEY", false);
xhr.send();
console.log(xhr.statusText);

I am assuming you need to console the API response. To do that you have to use on readystatechange method. Try using this code snippet
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}

Related

Sending JSON to AJAX from Python Flask [duplicate]

This question already has answers here:
Parsing JSON from XmlHttpRequest.responseJSON
(5 answers)
Return JSON response from Flask view
(15 answers)
Closed 4 years ago.
I'm trying to send data from a server made with Flask in Python, to the client and collect this data with AJAX. Many of the examples I have seen does this with jQuery, but I'd like to do it without jQuery. Is it possible to do this with just ordinary Javascript without jQuery, and how would I build this functionality?
You could use the built in XMLHttpRequest object in javascript if you don't want to use jQuery. It's quite simple to use actually,
var url = 'www.yoursite.com/data.json';
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open("GET", url, true);
xhr.onload = function() {
console.log("Status Code", this.status);
console.log("Body", this.response);
}
xhr.send();
You can use the regular XmlhttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Better yet, you can use the Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
From the MDN documentation:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
Fetch makes use of Promise so you should use that.

Redirecting to a separate Django view after Ajax request is successful

Django/Python server-side dev here. And also a JS newbie (8 days old). This question is about Ajax-initiated page reloads.
Here's a JS snippet where I'm processing the JSONResponse from a Django view I POSTed some data to. Depending on success or failure, you'll see that I'm calling a redirect to another Django view:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
var resp = JSON.parse(this.responseText);
if (!resp.success) {
console.log("Failed!");
} else {
console.log("Success! Redirect to: ", resp.success_url);
window.location.href = resp.success_url;
window.location.reload();
}
}
};
xhr.open('POST', e.target.action);
xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken'));
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(form_data);
Specifically, the following lines do the trick:
window.location.href = resp.success_url;
window.location.reload();
My problem is that when this gets executed in Firefox, I am made to see the following dialog box:
It seems the POST parameters are being sent again ?! How do I just do a plain old GET type redirect to resp.success_url instead? Please advise and let me know if you need more information.
Note: let's stick to pure JS for the scope of this question - I'm learning vanilla JS these days and don't want to get into JQuery prematurely.
Try
window.location.replace(resp.success_url);

What is the Magic Behind jQuery's `$.getJSON` [duplicate]

This question already has answers here:
JavaScript XMLHttpRequest using JsonP
(5 answers)
Closed 5 years ago.
I am trying to grab json data from reddit using vanilla javascript and I found something perplexing. I found this question here grabbing Reddit data via javascript
where there is a very solid solution making use of jQuery.
Here is the jsfiddle they shared. http://jsfiddle.net/DHKtW/353/ we can see the $.getJSON is working.
So I implement my own getJSON function like this:
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
// let url = 'http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback';
// let url = 'https://www.reddit.com/r/CryptoCurrency/.json?jsonp=?';
let url = 'http://www.reddit.com/r/pics/.json?jsonp=?';
getJSON(url , function(err, data) {
if (err !== null) {
console.log('Something went wrong: ' + err);
} else {
// console.log('Your query count: ' + data.query.count);
console.log('Your query count: \n');
console.log(data.query);
}
});
You can see in the code I have a couple of test urls that I tried. the yahooapis.com worked fine, reddit didn't. I am thinking this has something to do with jsonp. Here is a jsfiddle I set up to demonstrate that my code doesn't work. https://jsfiddle.net/9ky480c8/ here it is throwing an error that the request must be sent over https, which wasn't the case in the other jsfiddle.
Anyone know how to handle this with pure javascript?
It looks like you can ignore the JSONP issue by just omitting that query parameter. For that Reddit API, https://www.reddit.com/r/CryptoCurrency/.json seems to work just fine on its own and returns pure, normal JSON.
If you want to use JSONP, check out JavaScript XMLHttpRequest using JsonP for a method of doing it with pure Javascript and XHR.

chrome extension http request to website

I wanted to make a chrome extension that gets the html code from this website: https://free-proxy-list.net/
without actually going to that webpage.
I tried using the steps here:
https://developer.chrome.com/extensions/xhr
but the request kept showing as undefined when I tried to print it out.
The script I was using was:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open('GET', "url", true);
xhr.send(null);
document.write(xhr.send());
Note: not putting url in code since SO won't let me post a question with more than 2 links.
How would I get the code from this website in a string variable that I can parse?

javascript XMLHttpRequest returning status of 0 [duplicate]

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 6 years ago.
I am trying to call a REST API with JavaScript and XMLHttpRequest.
The URL is: "http://quotes.stormconsultancy.co.uk/random.json"
This works from the browser window, but when I try to run it as javascript in the browser, it always returns a status of 0
(Even when I substitute the URL with any another URL for a simple GET request - for e.g. http://www.yahoo.com, I still get the same result.
Here is the code:
(function callRestAPI() {
var request = new XMLHttpRequest();
var url = "http://quotes.stormconsultancy.co.uk/random.json";
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
alert("The response was: " + request.responseText);
} else if (request.status === 0) {
alert("The response was a status code of 0");
}
}
};
request.open("GET", url, "false");
request.send();
})();
I am at a loss on how to figure this out. Any help would be appreciated.
Thanks,
Jay
(Note: I get the same result with Firefox 47 and Chrome 51
Isn't this a Cross-Origin Request issue? Since you're calling the URL in ajax from another domain it gets blocked, thats why when you're doing it from the browser window it works (same domain) but from where you're hosting your script it doesn't?
Cross-Origin Request, the Server has to provide some whitelist to let you do what you want, read here:
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Categories