I'm very new to web development.
When I input this link
https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412
into my browser, I can see the JSON object.
What do I need to do so can I use this JSON object in my javascript? I've tried using JQuery's $.getJSON with no luck.
EDIT
Using JSONP worked! Appending &jsonp=readJSON&?callback=? to the URL gave me back the JSON I wanted. Thank you for all the informative answers.
$.getJSON( "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412&jsonp=readJSON&?callback=?", function() {
console.log( "success" );
})
function readJSON(response){
console.log (response);
}
The question is, is this domain (api.locu.com) the same from where you serve your files? I suppose it isn't. In this case, you have two options:
Your backend can proxy the request from this site
You have to use a JSONP object if it's supported by the API
I'm no clear about your question, but I think you can use a call ajax, something like:
$.ajax({
url: "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412",
type: 'get',
cache: false,
success: function (response) {
console.log(response);
}
});
This should get the concept across if you are using JQuery... but you can use just about anything.
var url = "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412";
var result;
var settings = {
success: function(data){
result = data;
//do anything else related to this data here as you need it fetched, and is not linear.
}
}
$.ajax(url, settings);
Now, I noticed you used getJSON, which is pretty much the exact same. I did not however see you use a success function, so if you did your way, have you tried:
$.getJSON(url, function(data){
result = data;
});
I may be mistaken, but you say: "With no luck" so i have a limited understanding as to what you tried with $.getJSON
Not directly from inside a web browser, no. You would need to use a proxy: another server that makes this request in your behalf and then gives you the result.
Why not?
Web browsers are pretty tight on security. One of the strategies for protecting users from malicious activity is restricting the domains your Javascript can make HTTP requests to.
An HTTP request from your domain (the origin) to another domain is called a cross-origin request. These are forbidden by default, and you won't be able to read the response body, unless the received HTTP response includes the header Access-Control-Allow-Origin.
How then?
By using a proxy as an intermediary. The proxy is not a web browser, it doesn't care about Access-Control-Allow-Origin, and will read the response anyway.
There are a number of proxies you can use. An easy one is YQL (the Yahoo Query Language). Here's an article on the topic, using jQuery: http://ajaxian.com/archives/using-yql-as-a-proxy-for-cross-domain-ajax
Related
I want to print in console content that are returned in http response. For example when I go to https://google.com and in the tab Network I can see content such as scripts, text, document, png. I want to print names of all .png files.
I tried to use something like that:
function hand () {
console.log(this.getResponseHeader('content-type'));
}
var x = new XMLHttpRequest();
x.open('GET', 'https://google.com', true);
x.onreadystatechange = hand;
x.send();
But it doesn't work for me. This action below is assigned for the button on me page.
Cross-origin requests simply are not allowed by default. The remote server may provide permission to your application through CORS or by supporting Ajax alternatives like JSONP.
Edited:
The only (easy) way to get cross-domain data using AJAX is to use a server side language as the proxy as Andy E noted. Here's a small sample how to implement that using jQuery:
The jQuery part:
$.ajax({
url: 'proxy.php',
type: 'POST',
data: {
address: 'http://www.google.com'
},
success: function(response) {
// response now contains full HTML of google.com
}
});
Simple as that. Just be aware of what you can or cannot do with the scraped data and be very much aware that such a proxy is a severe security hole. At least make a list of acceptable addresses and don't just blindly accept any passed address. Have a look at a decent proxy script here: PHP Simple Proxy
$.getJSON('http://robloxplus.com:2052/inventory?username=itracking', function(data){
$.each(data, function(item){
console.log(item['id'])
});
});`
returns undefined when attempting to run it on an external website. It is supposed to output each id of every item in that list (http://robloxplus.com:2052/inventory?username=itracking)
How do I fix this?
Edits>
I want to iterate over each individual id, each of these numbers "168167114": and "135470963": etc. etc. and fetch the data that follows that (i.e. the name:"", totalSerial:"")
is the request being made on the same domain as robloxplus.com ?
I'm new to this.. I don't understand much about JavaScript and/or
JQuery. #Pedro Lobito no, it's not. –
Explanation:
HTTP requests from Javascript are traditionally bound by the Same
Origin Policy, which means that your ajax requests must have the same
domain and port. The common ways to get around this are JSON-P,
Proxying and message passing via s. These all have their
quirks, but the thing they generally have in common is legacy browser
support.
Solution
1 - If robloxplus.com is yours, you can enable CORS
2 - If not, you can use YQL (Yahoo! Query Language) to bypass CORS
When one of the above options is fulfilled, you can make your json request, i.e.:
$.ajax({
url: 'http://robloxplus.com:2052/inventory?username=itracking',
type: 'get',
dataType: 'json',
success: function(data) {
$.each(data.id, function(item) {
console.log(item);
});
},
error: function(e) {
console.log(e.message);
}
});
I'm writing a jQuery interface to use a couple of OData services created in SAP. The services is working ok, and are also being used by some other applications.
I've already searched and I'm mostly come across people who are saying it's a cross domain issue. The first thing I tried was to plain and simply do a cross domain ajax call:
$.ajax({
url : 'http://saphostname:8000/sap/opu/odata/sap/entityset/?$format=json',
crossDomain : true,
xhrFields {
withCredentials : true,
}
// .. success, statusCodes, whatever ..
})
The responses that came from this call were 200, and if I viewed the content in the developer tools I saw my json message as I would expect it to be in there, but none of my callback functions were being triggered.
Upon searching more, somebody suggested using $.getJSON(). This didn't work either. The error that kept coming back was 401, so I assumed it was a cross domain issue.
The last thing I stumbled upon was JSONP. The response is coming back with an OK status code, and once again if I view the body content I see my json string as I would expect it. The only problem is my browser says there is a syntax error in the response text.
All of my search results have brought up issues regarding cross domain requests, and errors resulting there-in. Maybe it is the issue, but because I'm getting the results back that I would expect in the responses, I'd have to assume that connectivity is no problem.
tl;dr: ajax cross-domain requests are successful but don't trigger callback functions and jsonp gives me a syntax error. I'm not sure where to keep looking.
You are trying to do a JSONP request to a JSON service. The way that the response is handled for a JSONP request is that it is executed, but executing a JSON response only evaluates it and discards it.
The crossDomain property only causes the request to act like a cross domain request, i.e. using JSONP, regardless if it's actually to a different domain or not.
You should specify dataType: 'json' in the properties, to keep it from using JSONP.
Alternatively, if the service also supports JSONP, you could change $format=json in the URL to $format=jsonp, and specify dataType: 'jsonp' in the properties.
Edit:
Another thing that you can try is to use a proxy that turns a JSONP request to a JSON request. I have set up such a proxy that you can use to test if you can get the right response:
$.get(
"http://jsonp.guffa.com/Proxy.ashx?url=" + escapeURIComponent("saphostname:8000/sap/opu/odata/sap/entityset/?$format=json"),
function(data) {
console.log(data);
},
"jsonp"
);
I already had a problem like this before and what helped me to solve the problem was using callbacks like these:
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second complete" );
});
Now you can see which one is being triggered and debug the problem.
I use JSONP to access to a json page (via jQuery). I have an html button
<input type="button" value="Récupérer les données" onclick="getInfo();" />
my Code
function getInfo() {
$.ajax({
dataType:'jsonp',
url: 'http://89.92.40.250:8010/dreamteam/interface/get_event_detail.php?id=106',
data: { param:'event' },
success:function(response) {
alert("Réponse : "+ response.data);
}
});
};
the alert doesn't work...
That server doesn't support JSONP, at least not with the standard callback parameter construct.
Consider using a server-side solution to this problem.
BTW
Original question: Cannot access json file with javascript
Hello again, at SO you can edit your existing questions or engage with those who answer; you don't have to ask another question with basically the same problem.
As a safety precaution you cannot make cross origin requests see CORS as alternative you can make a server side proxy, have that proxy call the web service you intend to call and return you the response in whatever format you like, be it xml or json. As #SLaks mentioned in the comments you cannot consume jsonp unless the remote server approves of it.
I want to use JSON to get localization coordinates from http://aprs.fi/page/api. I found example at http://api.jquery.com/jQuery.getJSON :
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "cat",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});
</script>
When $.getJSON succed, it runs function(data), it puts 4 images on website. I paste this code in my html file and it works, so I changed it to get JSON data from aprs.fi:
<script>
$.getJSON("http://api.aprs.fi/api/get?name=OH7RDA&what=loc&apikey=_key_&format=json",
function(data)
{
alert("Anything");
});
};
</script>
Maybe my query is wrong, but even "Anything" doesn't print on my screen. I have no idea how to change it to make it works.
Just because a service can return JSON-formatted results does not mean that you can access it via JSONP. The site has to explicitly recognize such a request so that the response works as a JSONP response. (That is, the response must take the form of a function call, with the JSON return data passed as the argument to the function.)
The XHRs that getJSON is using are subject to same-origin-policy in web browsers; you can point XHR only to from only the exactly same server, port, protocol combination as the web page they are used in. If your web page runs on http://example.org:5625 it can only point XHR requests to http://example.org:5625/some-path-here.
The workaround is called JSONP where the resource is loaded as a tag. However, the service in question needs to be aware of it. You can tell if it is because after appending the callback parameter it should show something like
callbackname({"the": "respose", "goes": "here"});
that is, a function call to the named callback. However, if I understood correctly, the service you are using does not support JSONP. Then your only option is to make a serverside script that works as a proxy.