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.
Related
i'm trying to access a local JSON File with JS, turn it into an JS Object by parsing it and logging it to the console. I'm using Live Server in VS Code to set up the Server, therefore the localhost URL.
var requestURL = "http://localhost:5500/sqVol.json";
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
var jsonObj = request.response;
request.onload = function () {
JSON.parse(jsonObj);
logData(jsonObj);
};
function logData(jsonObj){
console.log("jsonObj= " + jsonObj);
//console.log("jsonObj[Datum]= " + jsonObj[Datum]);
//console.log("jsonObj.Datum= " + jsonObj.Datum);
}
Output: jsonObj= null
The JSON File:
{
"Datum": ["03.05.2017","05.06.2017"],
"Volume": [1338,1445]
}
Here's what I imagine happens:
I'm getting the Answer from localhost and parsing it via JSON.parse into an JS Object. As soon as the request finished im calling my logData function and passing the parsed Data to log it.
As #connexo pointed out I didn't understand the asynchronous nature of the call. And frankly i still don't but i guess a good starting points will be:
How do I return the response from an asynchronous call?
MDN Synchronous and Asynchronous Requests
As #Mani Kumar Reddy Kancharla pointed out my response is already a JS Object since i declared request.responseType = 'json';
This is how it looks right now:
var requestURL = "http://localhost:5500/sqVol.json";
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function () {
console.log(request.response);
var jsonObj = request.response;
logData(jsonObj);
};
function logData(jsonObj){
console.log("jsonObj= " + jsonObj);
console.log("jsonObj[Datum]= " + jsonObj.Datum);
Ouput: {…}
Datum: Array [ "03.05.2017", "05.06.2017" ]
Volume: Array [ 1338, 1445 ]
jsonObj= [object Object]
jsonObj[Datum]= 03.05.2017,05.06.2017
As you can see i can also access the .Datum Property. I Consider it solved. Thank you!
edit: Added the link provided by connexo.
I used the browser XMLHttpRequest object for Ajax about 12 years ago.
https://api.jquery.com/jquery.getjson/
You have two issues in your code:
You're using JSON.parse() too many times on same date which is already converted from JSON string to a JavaScript object and tries to parse a Javascript object raising a Syntax error. You've already mention request.responseType = 'json' i.e. responseType specifies you're receiving a JSON string as response so JavaScript Engine will already parse it and provide you a JavaScript object as request.response and you need not parse it. So you could use JSON.parse(request.responseText) if you want to parse it yourselves or directly use request.response as a JavaScript object.
You're trying to store request.response into a variable outside the load function which will just provide the value of request.response at that time which could be null if the response is not received yet. You need to get the response in the onload fucntion implementation as it is executed once you receive the response.
So what you're looking for overall is this ->
var requestURL = "http://localhost:5500/sqVol.json";
var request = new XMLHttpRequest();
var jsonObj;
function logData(jsonObj){
console.log("jsonObj= " + JSON.stringify(jsonObj));
console.log("jsonObj[Datum]= " + JSON.stringify(jsonObj["Datum"]));
console.log("jsonObj.Datum= " + JSON.stringify(jsonObj.Datum));
// or simply
console.log(jsonObj);
console.log(jsonObj['Datum']);
console.log(jsonObj.Datum);
}
request.onload = function () {
jsonObj = request.response;
logData(jsonObj);
};
request.responseType = 'json';
// finally send the request
request.open('GET', requestURL);
request.send();
Here JSON.stringify() converts a JavaScript Object back to a JSON string.
Refer to this link to get more information on how to use XMLHttpRequest
EDIT: Referring to another answer posted, people simply use libraries like jQuery AJAX to make asynchronous requests to get data from the web, especially in XML or JSON format.
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);
}
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.
This question already has answers here:
JavaScript XMLHttpRequest using JsonP
(5 answers)
How to make a JSONP request from Javascript without JQuery?
(12 answers)
Closed 6 years ago.
I use pure JavaScript to make ajax call in another domain (cross-domain).
So i need to specify the dataType. But i don't know, where to specify ?.
I use the following to make ajax call with javascript:
var xmlhttp = new XMLHttpRequest();
var url = 'www.mydomain.com/path/to/reach';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log('Log : ' + url + ' || Updated.');
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
url = url + '?callback=my_callback_method';
xmlhttp.open("GET", url, true);
xmlhttp.send();
Also i make dummy callback,
function my_callback_method(res){
//
}
But, it won't work. I get error as Reason: CORS header ‘Access-Control-Allow-Origin’ missing.
What's wrong with my code ?
Is it possible ?
Any Solutions ?
(I need Solution for JavaScript Only !)
I get error as Reason: CORS header ‘Access-Control-Allow-Origin’
missing.
This is because you're using XMLHttpRequest and usage of XMLHttpRequest requires CORS. The JSONP technique doesn't involve usage of XMLHttpRequest. The trick in JSONP is to create a script tag and let a browser load that script:
var script = document.createElement('script');
script.src = '//domain.com/path/to/jsonp?callback=my_callback_method'
document.getElementsByTagName('head')[0].appendChild(script);
Also, you need to create a global function, in your case its my_callback_method, and call it from the jsonp script.
Certainly, you server side should have implementation that when a request to //domain.com/path/to/jsonp is obtained, it should return a js document with a call to a global function specified in callback=my_callback_method:
my_callback_method()
I'm using themoviedb.org API to fetch the movie info. This is the code I'm using:
var req = new XMLHttpRequest();
req.open("GET", "http://api.themoviedb.org/2.1/Movie.search/en/json/XXX/immortals?callback=foobar", true);
req.send();
req.onreadystatechange=function() {
if (req.readyState==4 && req.status==200) {
console.log(req.responseText);
}
}
And I'm getting this response in the console:
foobar([{"score":null,"popularity":3,"translated":true,"adult":false,"language":"ru","original_name":"Immortals","name":"Immortals","alternative_name":"\"War of the Gods\"","movie_type":"movie","i".......}])
How do I parse this response to get the name attribute?
Updates:
Thank you everybody but the actual answer was given by hippietrail.
eval(req.responseText)
More details: Filtering to specific nodes in JSON - use grep or map?
add this function to your page :
( i see its an array - so i'll iterate each item... - if you want the first one only - so please specify.)
function foobar(x)
{
$.each(x, function ()
{
alert(this.score);
});
}
http://jsbin.com/ojomej/edit#javascript,html
The URL you're using is for a JSONP call (see: http://en.wikipedia.org/wiki/JSONP). JSONP is used when cross domain request through XMLHttpRequest are not allowed. But you're using XMLHttpRequest already so I believe you don't need a JSONP call. So, if you remove the querystring from the URL:
var req = new XMLHttpRequest();
req.open("GET", "http://api.themoviedb.org/2.1/Movie.search/en/json/XXX/immortals", true);
req.onreadystatechange=function() {
if (req.readyState==4 && req.status==200) {
console.log(req.responseText);
}
}
req.send();
You should get a JSON string:
[{"score":null,"popularity":3,"translated":true,"adult":false,"language":"ru","original_name":"Immortals","name":"Immortals","alternative_name":"\"War of the Gods\"","movie_type":"movie","i".......}]
That you can parse using JSON.parse (see: https://developer.mozilla.org/en/JSON):
var data = JSON.parse(req.responseText);
Now you have a JavaScript object, in your case an array of objects, that you can use:
console.log(data[0].name) // "Immortals"
However, because the question is tagget "jquery", if you're using that library you can simplify a lot:
$.getJSON("http://api.themoviedb.org/2.1/Movie.search/en/json/XXX/immortals", function (data) {
console.log(data[0].name)
});
jquery will also take care of the browsers differences (e.g if the browser doesn't support JSON object).
Hope it helps.
I don't have an API key to test this, but it seems you're not very familiar with either jQuery nor JSON. Anyway something like this might get you started:
$.getJSON("http://api.themoviedb.org/2.1/Movie.search/en/json/XXX/immortals?callback=?",
function(data) {
alert(data[0].name);
}
);