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.
Related
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.
I am trying to make a post request to a url with the following code .
Passing object to http.send(params) function gives (400) bad request error.
I am not able to trace the issue here .
var http = new XMLHttpRequest()
var url = 'http://somerandomurl'
http.open('POST', url, true)
http.setRequestHeader('content-type', 'application/json')
http.setRequestHeader('accept', 'application/json')
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
returndata = http.responseText
console.log(JSON.parse(returndata))
}
}
http.send(params)
Solution: http.send(JSON.stringify({'email': params.email, 'password': params.password})) it worked for me .
It seems to me that your issue is that you are trying to send a whole object instead of JSON. The correct way to do this would be to use http.send(JSON.stringify(params))
You should use one of three ways to do it
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#A_brief_introduction_to_the_submit_methods
Or either, you can take Axios.
You can use the new fetch API for this, makes it dead easy and less code
// Call the fetch function passing the url of the API as a parameter
fetch(url)
.then(function(response) {
// Your code for handling the data you get from the API
})
.catch(function() {
// This is where you run code if the server returns any errors
});
Also if your a newbie it will get things working quicker and help you solve your problem faster.
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 developed a small Javascript/jQuery program to access a collection of pdf files for internal use. And I wanted to have the information div of a pdf file highlighted if the file actually exist.
Is there a way to programmatically determine if a link to a file is broken? If so, How?
Any guide or suggestion is appropriated.
If the files are on the same domain, then you can use AJAX to test for their existence as Alex Sexton said; however, you should not use the GET method, just HEAD and then check the HTTP status for the expect value (200, or just less than 400).
Here's a simple method provided from a related question:
function urlExists(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.status < 400);
}
};
xhr.open('HEAD', url);
xhr.send();
}
urlExists(someUrl, function(exists) {
console.log('"%s" exists?', someUrl, exists);
});
Issue is that JavaScript has the same origin policy so you can not grab content from another domain. This won't change by upvoting it (wondering about the 17 votes).
I think you need it for external links, so it is impossible just with .js ...
If the files are not on an external website, you could try making an ajax request for each file. If it comes back as a failure, then you know it doesn't exist, otherwise, if it completes and/or takes longer than a given threshold to return, you can guess that it exists. It's not always perfect, but generally 'filenotfound' requests are quick.
var threshold = 500,
successFunc = function(){ console.log('It exists!'); };
var myXHR = $.ajax({
url: $('#checkme').attr('href'),
type: 'text',
method: 'get',
error: function() {
console.log('file does not exist');
},
success: successFunc
});
setTimeout(function(){
myXHR.abort();
successFunc();
}, threshold);
You can $.ajax to it. If file does not exist you will get 404 error and then you can do whatever you need (UI-wise) in the error callback. It's up to you how to trigger the request (timer?) Of course if you also have ability to do some server-side coding you can do a single AJAX request - scan the directory and then return results as say JSON.
Like Sebastian says it is not possible due to the same origin policy. If the site can be published (temporarily) on a public domain you could use one of the link checker services out there. I am behind checkerr.org
As others have mentioned, because of JavaScript's same origin policy, simply using the function from the accepted answer does not work. A workaround to this is to use a proxy server. You don't have to use your own proxy for this, you can use this service for example: https://cors-escape.herokuapp.com (code here).
The code looks like this:
var proxyUrl = "https://cors-anywhere.herokuapp.com/";
function urlExists(url, callback) {
var sameOriginURL = proxyUrl + url;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.status < 400);
}
};
xhr.open('HEAD', sameOriginURL);
xhr.send();
}
urlExists(someUrl, function(exists) {
console.log('"%s" exists?', someUrl, exists);
});
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);
}
);