Cross Domain Ajax (JSONP) Callback Issue - javascript

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.

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 GET request, difference between browser and localhost making the call

I attempt to make a GET request to an API from a locally hosted meteor app (=> App running at: http://localhost:3000/) and upon doing so I get the error:
"XMLHttpRequest cannot load [the-api-url]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://localhost:3000 is therefore not allowed access."
Yet when I paste [the-api-url] into my browser and hit ENTER, the appropriate API response is shown in my browser window (a little JSON object). I have read some other SO posts about cross-domain request issues, but I don't understand the solutions, or what the difference is between sending the GET from my code or from the browser. Can someone explain why this behavior occurs, and what the appropriate change to my code/design is? My existing code is as below:
$.ajax({
type: "get",
url: auth_ad_act_url,
data: {
ads_token: ACCESS_TOKEN
},
dataType: 'jsonp',
success: function(data, status) {
console.log(data);
}
});
EDIT:
I do a jQuery.ajax() of type "get" supplied with a URL, parameters object, and success callback function, and dataType 'jsonp' to deal with cross-domain requesting.
I posted new code. Now the error is that the response is not correct. (I know this because it worked from my browser, and that responsee lined up with the API documentation). The response is "Resource interpreted as Script but transferred with MIME type text/html: https://host.com/apps/[my-app-id]/authorize_ad_account?callbac…" but it should be an object with the key 'url' and one other thing. I also get the error "Uncaught SyntaxError: Unexpected token :" when I include 'jsonp'. But that incorrect response mentioned above still gets logged to console so I don't understand when that syntax error happens, or where.
The Same Origin Policy does not include what you type into your address bar. If it did, you literally would not be able to access any website at all unless it was saved on your local machine!
In your situation, in order to get the resource that you need from jQuery's get, you'll either need to use a server-side proxy hosted on a matching domain, or since you're consuming JSON see if the API you're using supports JSONP.
There is a possibility to get JSON Data with a cross-domain request. You have to use JSONP and define a callback method, which has to be in the call and in the JSON Data.
Your request:
$.ajax({
type: "GET",
url: auth_ad_act_url + "&callback=?",
jsonpCallback: "jsonCallback",
dataType: "jsonp",
success: function(data) {
// Do something with the data
}
)};
The JSON File on the external server:
jsonCallback(INSERT_HERE_THE_JSON_DATA);
If you do not have the possibility to add the jsonCallback on the external server, check out CORS.

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

Chrome cannot parse single line JSONP object

I'm having issues getting this JSON object to load via JSONP in Chrome 18 (latest stable). For some reason it presents me the error: Uncaught SyntaxError: Unexpected token :. According to JSONLint, the response is a valid JSON object.
Here is the code example: http://jsfiddle.net/jakebellacera/2j7DL/1/
To add: I'm attempting to get around cross-domain, I have permissions to both servers, but we cannot allow cross-domain on a specific domain for specific reasons. If there is a better way to do this, please let me know.
The server at lpunderground.com is returning JSON, not JSONP.
What's special about JSONP is that it's a valid javascript statement - the data returned from the server is wrapped in a function call (or sometimes a variable assignment) and when returned it is evaluated as normal javascript. Typically the client passes the server in the request parameters a function name to use in wrapping the data.
See the Wikipedia article and the jQuery docs for the details.

getJSON and invalid label

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.

Categories

Resources