getJSON and invalid label - javascript

I am trying to get json data from a url. Url is working ok in FF. I am trying code like this
$.getJSON("http://testsite.com/1234/?callback=?", function(data){
//here i am getting invalid label error**
}
);
When i am trying without callback=? i am getting empty data
$.getJSON("http://testsite.com/1234/", function(data){
//here i am data = ""
}
);
Whats going wrong?

It looks like the site you're fetching from doesn't support JSONP, with this URL:
http://testsite.com/1234/?callback=?
It's trying to use JSONP, but the server is returning a plain JSON response (not wrapped in a function).
With this URL:
http://testsite.com/1234/
It's not trying JSONP at all, and being blocked by the same-origin policy.
To fetch data from a remote domain, it needs to support JSONP so it can be grabbed with a GET request, so you'll need to either add support to that domain, or proxy the request through your own.

Related

Fetching JSON data using JS from a third party

I'm trying to use a certain service to check for proxies. They have a simple API from which they return JSON. I'd like to get this JSON on my server.
No matter what I do, I either get a CORS request problem or a SyntaxError: missing ; before statement message.
Here's my code:
<h1>Test Page</h1>
Test Button
<script>
function checkProxy() {
console.log("Checking...");
$.ajax({
url: 'http://api.ip2proxy.com/?ip=105.159.246.30&key=demo',
dataType: 'jsonp',
success: function(data){
console.log(data);
}
});
}
Clicking my 'button' calls the funtion, which returns the aforementioned syntax error. Changing the datatype to JSON gives me a CORS error.
The strange thing is, when I use a different URL -- example that I found in another StackOverflow thread: http://www.locationbox.com.tr/locationbox/services?Key=3430000202000191008400080609030X20201090060050260003069&Cmd=IlList -- it logs the data just fine.
I'd like to get this JSON on my server.
You'll need to write code that runs on the server to do that. The reason your code is failing is that you're running it on a browser, where the Same Origin Policy comes into play: Your page's origin isn't granted access by that API endpoint via CORS. Unless they allow you access, or they provide a JSONP endpoint you can use instead, you cannot directly query it from a browser.

Cross Domain Ajax (JSONP) Callback Issue

I have a code where i need to make cross domain requests to get the text/html as response. I've been using the JSONP method and was getting the results (json) before on some other program. When i run the program, console reports an error which is
Uncaught SyntaxError: Unexpected token <
?callback=jQuery17207555819984991103_1414157672145&_=1414157675836"
As you can see it has added an extra parameter value after the callback parameter which is causing an issue. When i see the response in Network tab, its pretty good and exactly what i wanted. I tested it on 4 cross domain links and that extra paramter is coming to all of them.
Following is my code:
$.ajax({
type: 'get',
url: link,
dataType: 'jsonp',
success: function(dataWeGotViaJsonp){
alert(dataWeGotViaJsonp)
var len = dataWeGotViaJsonp.length;
}
});
The links I have passed to it:
http://stackoverflow.com/questions/20944962/data-grid-view-update-edit-and-delete-in-vb-net-windows-form-that-using-multipl
http://www.espncricinfo.com/pakistan-v-australia-2014/engine/match/727927.html
http://pucit.edu.pk/
Response is good but due to that error, success callback isn't being called. Any solutions?
"Uncaught SyntaxError: Unexpected token <" is an indication that the returned data is very likely HTML mark-up and not proper JSONP. In order to return HTML from a JSONP web service, you need something on the server that is wrapping the HTML in proper procedure call syntax. E.g.,
jQuery17207555819984991103_1414157672145 ("<div>... your HTML here ...</div>")
Since the HTML will likely have quote characters in it somewhere, you will need to escape, URL encode, UUEncode, or otherwise convert the HTML text to be an appropriate Javascript string, and then convert it back in the client.
As for the "_=1414157675836", this is being added to ensure the response is not cached. Unless your server's web service is rejecting the request because the "_" parameter is not recognized, this is a red herring. The problem is the bad JSONP syntax coming from the host.

Forcing a JSONP call to convert text response to JSON

If I've got the following request
$.ajax({
type: "GET",
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "my_callback",
url: my_https_url,
headers:{"Content-Type":"text/html; charset=utf-8"},
success: function(data) {
eval("json="+data);
}
error: function() {
console.log("fail");
}
});
I'm getting a server response with the 200 status code. The response header says it is sending back text/html as the content-type. However, I know the content is actually formatted JSON data. The problem is the server is not configured to accept JSONP requests (and I can't change it). I am using the JSONP approach for cross-domain-related reasons. The error status I get back is a "parseerror" because it's not recognized as JSON. Is there a way to override the function responsible for parsing the data so that I can force it to be treated as JSON? Possibly using eval()?
If your server is not capable of creating a JSONP formatted response and you have to use JSONP because of same-origin restrictions, then you're just plain out of luck. A JSONP formatted response is in the form of a executable script that calls the specified callback.
You generally can't fetch JSON from a different origin. You either need JSONP or you need a modern browser with a server configured to allow cross origin requests. If you can't configure the server to allow cross origin requests, then you need the server to create JSONP. If it won't do that, then you can't get the data from it. JSONP is a work-around for cross-origin requests and it REQUIRES server cooperation to create a JSONP formatted structure for the response.
If you are getting JSONP structure from the server and jQuery is getting a parse error when trying to parse the response as JSON, then that's because whatever the server is sending is not legal JSON inside of the JSONP structure. The fact that you're getting a parse error would mean that jQuery is trying to parse it as JSON and is getting an error when trying to do so. If that's the case, then you have two choices:
Fix the data the server is sending to be 100% legal JSON.
Accept the data as text and fix it to be legal JSON or parse it yourself in some manner that accepts it the way it is.
In either case, the first step is probably to console.log() the text that is being sent and understand exactly why it's not being accepted as legal JSON. Then, you'll better know what your options are. If you want help with understanding that, then add the exact server response to your question.

jQuery get JSON

I'm trying to pull in the total shares from a number of pages and have them displayed on my home page. I'm using addthis for the share buttons. I found a way to pull in the required info using JSON here.
Since I have multiple urls I'm storing them in an array, then cycling through and calling each one. Here's my code...
jQuery(document).ready(function(){
var shareCountArray = [ "url1", //Array to put all url's to get share total
"url2"]
shareCountArray.forEach( function(shareUrl) {
var url = "//api-public.addthis.com/url/shares.json?url=http%3A%2F%2F"+ shareUrl +"?callback=?";
jQuery.getJSON(url, function(json) {
alert(json.shares);
});
});
});
It's throwing up the error "Uncaught SyntaxError: Unexpected token : ". I thought this may have been because I included ?callback=? but when I remove that the console throws up errors because they're different origins.
Thanks for your time!
When you include callback=? then jQuery thinks the response is JSONP. JSONP is nothing else than including a JavaScript file. I.e. the response you receive is interpreted as JavaScript. That also means that if the server returns anything else than valid JavaScript, you will get an error. JSON on its own is not valid JS syntax, that's why you get the that error (you can verify that easily by putting {"foo": 42} in the console).
when I remove that the console throws up errors because they're different origins.
JSONP as well as CORS have to be supported by the server. You can't make an Ajax or JSONP request to the server if it doesn't. See Ways to circumvent the same-origin policy for alternatives.
But it actually looks like the service does support JSONP:
When calling services that support html responses, you may omit the .html extension. Optionally, you can use json mode and pass callback=function to specify a jsonp callback wrapper. Content-Type headers are set on responses as appropriate.
Looking at your URL, it is malformed. You should use &callback=? instead of ?callback=?. Multiple request parameters in a URL are separated by &. ? only indicates the beginning of the query string. E.g.
http://example.com/?param1=value1&param2=value2
Learn more about URLs: https://en.wikipedia.org/wiki/Url

Yahoo forecastjson gives XML error

After browsing through this site, I found that you can get Yahoo weather in a JSON format using forecastjson.
When I run:
$.getJSON("http://weather.yahooapis.com/forecastjson?w=2112762724", function(data){
...
});
I get the following error:
XMLHttpRequest cannot load http://weather.yahooapis.com/forecastjson?w=2112762724. Origin null is not allowed by Access-Control-Allow-Origin.
I've gotten this error before but its normally because I'm trying to load XML cross domain but this is clearly JSON. If you go to the link in the getJSON function, it shows JSON data. Does anyone know why I am getting this error?
Thanks
Using JSON doesn't mean that you will not encounter cross domain problem. That is an object standard.
If you want to make a cross domain request, you should use JSONP.
The url that you are trying to request, doesn't support JSONP request. But you can use YQL instead of that.
here is an example,
var query = escape('select item from weather.forecast where woeid="2295424"');
var url = "http://query.yahooapis.com/v1/public/yql?q=" + query + "&format=json&callback=c";
$.getJSON(url, function(data) {
console.log(data);
});​
And here is the URL that you can check json result.
DEMO

Categories

Resources