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¶m2=value2
Learn more about URLs: https://en.wikipedia.org/wiki/Url
Related
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.
Trying to get my html/JS file to read and print firstName from this link:
http://www.w3schools.com/jquery/demo_ajax_json.js, as trial for something else I want to do.
Received this error: Origin null is not allowed by Access-Control-Allow-Origin, so trying to use crossDomain.
Read this: jquery API but not sure how to implement correctly
My JS code (I know it's off, but no idea how to correct it):
var myArray = [];
var jsonArrayObj;
$.ajax{
crossDomain: true}).done(function(){
$(document).ready(function(){
myArray = $.getJSON("http://www.w3schools.com/jquery/demo_ajax_json.js", function(result){
myArray = JSON.parse(myArray);
console.log(myArray.firstName);
});
});
});
I don't understand what function() does in JS either
You cannot use CORS to access a website unless the website allows you to do so. If CORS was allowed on that endpoint, there would be an HTTP header for Access-Control-Allow-Origin: * (or a specific hostname). So the server you are attempting to talk to has to have a header allowing this to happen.
That endpoint works on the w3schools getJSON() demo page because the JavaScript is running from the same domain as the XHR target (so CORS is not needed).
More here: MDN: HTTP access control (CORS)
JSONP/JSON-P is an alternative to CORS but that endpoint doesn't appear to support it either (at least not with the typical callback querystring key).
Its because of CORS. Try to load file locally.
In your code you are using anonymous function. Internet is full of pages to read about javascript functions.
FUNCTIONS:
http://www.w3schools.com/js/js_functions.asp
https://en.wikibooks.org/wiki/JavaScript/Anonymous_Functions
If you are not familiar with JS syntax try to take online course to get your head around it.
JAVASCRIPT COURSE:
http://www.codecademy.com/en/tracks/javascript
Google for more. ;)
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.
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.
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.