dojo cross domain json returning as script - javascript

I'm trying to grab a songkick json feed using the below:
var jsonpArgs = {
url: obj.url,
load: function(data) {
console.log(dojo.fromJson(data));
},
error: function(error) {
new ErrorDialog({ title: 'Error', content: error });
}
};
dojo.io.script.get(jsonpArgs);
It loads the data fine, but it returns:
Resource interpreted as script but
transferred with MIME type
application/json. Uncaught
SyntaxError: Unexpected token :
This unexpected token coming from the contents of the file (line 1):
{ "resultsPage":
I'm guessing it's because the content coming back isn't be interpreted as json properly but I don't know what I'm doing wrong. I have tried specifying the callback parameter but it does nothing (not jsonp?).
Any ideas?

It looks like the feed does not support JSONP responses. Looking at their modest documentation I don't see how to specify a callback (the crucial part of JSONP). So obviously you are getting an error — JSONP uses <script> to retrieve the data, yet the data is of wrong type.
Another thing is you have to specify jsonp parameter, which is callback parameter. But it looks like a moot point, because I don't see your feed service supporting it.
So you best bet is to do a server-side call to this service using a proxy or something similar. This way you avoid cross-platform problems and can deal with JSON or XML directly.

Related

Jquery ajax usage for object

let quotesData;
function getQuotes(){
return $.ajax({
headers:{
Accept:"application/json"
},
url:'https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json',
success: function(jsonQuotes){
if(typeof jsonQuotes==="string"){
quotesData = JSON.parse(jsonQuotes);
console.log('quotesData');
console.log(quotesData);
}
}
})
}
getQuotes()
I was trying to complete project on fcc.Didn't know how to add quotes in html.Looked up in their premade project found this piece.Can someone explain what is going on in this code?
It's a hack to get around an incorrect Content-Type.
gist.githubusercontent.com isn't designed to host JSON data. It serves up plain text documents.
The success function tests to response to see if jQuery parsed it from JSON (which it will do if the Content-Type response header says it is) and if the response is a string it assumes it is unparsed JSON.
This is risky. A valid JSON text might encode only a single string (and trying to double parse it will error) and the document might not be JSON in the first place (which would also cause an error).
A better solution would be to use an appropriate hosting service.

DOJO cross-domain call returns data but fails due to syntax error in the Script tag

I am experimenting with a cross-domain call from Javascript, using the DOJO library. The web service I am calling returns JSON.
I am using "dojo.io.script.get" for this purpose.
The web service does not establish any particular query string parameter for the callbackParamName so I'm using ar arbitrary name such as "callback".
DOJO will inject back the SCRIPT tag with the result as seen below (extracted from Firebug):
<script id="dojo_request_script0" type="text/javascript" src="http://localhost:8281/services/TestGeocodeWorldLocator.TestGeocodeWorldLocatorHttpSoap12Endpoint?format=json&callback=dojo.io.script.jsonp_dojoIoScript1._jsonpCallback" async="" charset="utf-8">
{"GeocodeAddressResponse":{"Result":{"PropertyArray":{"PropertySetProperty":[{"Key":"Shape","Value":{"X":"-8841758.9684124179","Y":"5474103.2948672064","SpatialReference":{"WKT":"PROJCS[\"WGS_1984_Web_Mercator_Auxiliary_Sphere\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Mercator_Auxiliary_Sphere\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Standard_Parallel_1\",0.0],PARAMETER[\"Auxiliary_Sphere_Type\",0.0],UNIT[\"Meter\",1.0],AUTHORITY[\"EPSG\",3857]]","XOrigin":"-20037700","YOrigin":"-30241100","XYScale":"10000","ZOrigin":"-100000","ZScale":"10000","MOrigin":"-100000","MScale":"10000","XYTolerance":"0.001","ZTolerance":"0.001","MTolerance":"0.001","HighPrecision":"true","WKID":"3857"}}},{"Key":"Status","Value":"M"},{"Key":"Score","Value":"100"},{"Key":"Match_addr","Value":"1145 Nicholson Rd, Newmarket, ON, L3y"},{"Key":"PreType","Value":""},{"Key":"City","Value":"NEWMARKET"},{"Key":"Addr_type","Value":"StreetAddress"},{"Key":"X","Value":"-79.426873000000001"},{"Key":"Y","Value":"44.055940999999997"},{"Key":"Side","Value":"R"},{"Key":"House","Value":"1145"},{"Key":"PreDir","Value":""},{"Key":"StreetName","Value":"NICHOLSON"},{"Key":"SufType","Value":"RD"},{"Key":"SufDir","Value":""},{"Key":"Province","Value":"ON"},{"Key":"Postal","Value":"L3Y"},{"Key":"Disp_Lon","Value":""},{"Key":"Disp_Lat","Value":""},{"Key":"Loc_name","Value":"CAN_Streets"}]}}}}
</script>
The problem is that the browser (IE or Firefox) complains about 'Syntax Error - Expected ";"'. Basically it does not like the colons ":" in the JSON response injected in the SCRIPT tag.
Codewise, Javascript crashes at this line:
load: function(response, ioArgs)
I am thinking it may have something to do with the callbackParamName...but the server does not require any specific name.
Can someone please suggest how can I solve this problem?
This is the code I am using:
<head>
<script type="text/javascript" src='dojo-release-1.8.0-src/dojo/dojo.js' data-dojo-config='parseOnLoad: true, isDebug:true'></script>
<script type="text/javascript">
dojo.require("dojo.io.script");
function DOJOtoWS() {
var targetNode = dojo.byId("results");
var jsonpArgs = {
url: "http://localhost:8281/services/TestGeocodeWorldLocator.TestGeocodeWorldLocatorHttpEndpoint",
callbackParamName: "callback",
content: {format : "json"},
load: function(response, ioArgs){
console.log(response);
return response;
// Set the data from the search into the viewbox in nicely formatted JSON
targetNode.innerHTML = "<pre>" + dojo.fromJson(response) + "</pre>";
},
error: function(response, ioArgs){
targetNode.innerHTML = "An unexpected error occurred: " + response;
console.log("error");
console.log(response);
return response;
}
};
dojo.io.script.get(jsonpArgs);
}
dojo.ready(DOJOtoWS);
What you are describing sounds like JSONP. Thus the server needs to send data in JSONP format, not JSON.
There is a syntax error in the script injected by Dojo because dojo.script.io is expecting the server to return results in this format:
callback({"GeocodeAddressResponse": "blah blah blah"});
Explanation: Internally Dojo constructs a function named "callback" so it can execute the JSONP sent from the server. This function processes the data and sends it to your load function. Verify by trying a server that sends data back in JSONP format like this example does (http://ajax.googleapis.com/ajax/services/search/web).
Workarounds:
If you can't control the format returned by the cross-domain server, you will have to either set up a cross-domain proxy on the same-origin server or configure your browser to allow cross-domain AJAX calls.
You may also want to investigate Cross-Origin Resource Sharing (CORS) which is a new, safer standard meant to replace JSONP.

200/'parsererror' with jquery on ajax post to a https

I've read loads of other questions about this argument, but none could solve my problem.
I make a call to a php page in this way.
$.ajax({
url: 'https://mydomain/page.php',
type: "POST",
data: {
"arg1": arg1,
"arg2": arg2
},
success: function(data, textStatus, xhr) {
//do stuff
},
error: function(xhr, textStatus) {
alert("doLogin\n- readyState: "+xhr.readyState+"\n- status: "+xhr.status);
}
});
Now, if I put this stuff on the same server as the php it works fine. Troubles start when I launch it from localhost.
In that case I receive the following in the xhr:
readyState=0, status=0, statusText="error".
Reading some answers on the topic it seems to be because of a same-origin restriction, so I added a few parameters to the call. notably:
dataType:"jsonp",
crossDomain: true,
Apparently this works better, cause now I receive readyState=4, status=200, statusText="success". Trouble is, textStatus="parsererror". I also tried other things as jsonpCallback, cache, async, jsonp in many configurations with no luck.
Now, I receive no data back, cause this call will only give me a cookie that I need.
My question is: am I doing things correctly, for starters? In both cases, what is the reason of such an error? Does the fact that I call a 'https'/POST change something, rather than a plain http/GET?
Second question is, later on I will have to call some webservices through soap requests, which will return data in xml. Will using this same technique work (assuming jQuery doc is fine and I can write dataType:"jsonp xml" to have it converted on the fly (and assuming it is the right technique as well))? I assume it won't be, as jsonp expects something on the line of callbackFN({...}) rather than an xml, right?
If none of this is correct, what would the correct way to proceed be? I can't touch the server, thus I am limited to client side.
If you set dataType as JSONP, you can only get data as JSON.
So if the url (https://mydomain/page.php) doesn't response a JSON object, you will get parsing error, because it tries to parse it and fails.
JSONP is for JSON format data only! So if you receive a parseerror this means that the output of your PHP might not be well-formed JSON
And no, it is not easily possible to have XML as response to a JSONP call ..

How do I create a JSONP from an external JSON feed?

I have two domains: www.domain1.com and www.domain2.com
I have a plain JSON feed on domain1.
I want to pull the JSON feed from domain1 and put it on a module on domain2.
From what I've read, the way to go about it is by using JSONP but how do you go about doing that? Is there a way to do it with just JQuery/javascript? Or would I have to use server-side code (I'm using Coldfusion). Also could I just use .getJSON and not .ajax (I'm a beginner so I've never used .ajax yet)
EDIT
Okay I'm still getting confused. Just adding callback at the end of the url broke it. How could I make it so that instead of a remote path for a feed I am pulling an absolute path where this code is on www.domain2.com but the feed is on www.domain1.com?
var feed ="/event/json.tag/tag/sports/";
$.getJSON(feed,function(data) {
$.each(data.items, function(i,obj) {
do something here...
}
}
JSONP is just a callback function wrapped around a JSON object.
General convention is to have an endpoint that returns JSON, unless a callback parameter is defined on the request, and returns JSONP in that case.
i.e. http://www.domain1.com/api/getStuff might return:
{'foo': 'bar', 'fizz': 'buzz'}
then http://www.domain1.com/api/getStuff?cb=cb123 should return:
cb123({'foo': 'bar', 'fizz': 'buzz'});
I don't know ColdFusion, but I assume this example is good: http://www.coldfusionjedi.com/index.cfm/2009/3/11/Writing-a-JSONP-service-in-ColdFusion
There's no client-only solution unless somebody else already built JSONP support into the server you're working with...
Reading the jQuery Documentation $.ajax and $.getJSON will be a good start, anyway there are a lot of good tutorials about jsonp, this one for example is a great tutorial:
$.getJSON("http://api.oscar.aol.com/presence/get?k=key&f=json&t=aimuser&c=?",
function(result){
if (result.response.data.users[0].state == 'online') {
$("#status").css("background-image", "url('online.jpg')");
}
}
);
As mention in the website:
The f parameter tells the service what
format to return the results in--JSON
in our case. The c parameter specifies
the JSON callback to use--this is
important!
And in the jQuery documentation:
If the URL includes the string
"callback=?" (or similar, as defined
by the server-side API), the request
is treated as JSONP instead.
So keep in mind sending a callback and handling the data afterwords will be easy.
EDIT: another good example.
EDIT2:
When not specifying the callback value, jQuery will assign it for you (from the $.getJSON page) the flickr URL will become:
http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=jsonp1294786450519&tags=cat&tagmode=any&format=json
And the response:
jsonp1294786450519({
"title": "Recent Uploads tagged cat",
"link": "http://www.flickr.com/photos/tags/cat/",
"description": "",
"modified": "2011-01-11T22:47:12Z",
"generator": "http://www.flickr.com/",
"items": [
{ .... rest of json
So you need to wrap your json with the callback sent from domain1
You could retrieve the JSON 'feed' from domain1 and pass that data as a parameter to your own Javascript function (on domain2) when your request is completed (onComplete / onSuccess).

Invalid Label Error with JSON request

I've read about this a lot and I just can't figure it out. It has nothing to do with MY code, it has to do with the feed or something because if I swap it with a Twitter feed it returns an Object object which is perfect.
$.getJSON('http://rockbottom.nozzlmedia.com:8000/api/portland/?count=1&callback=?',function(json){
console.log(json)
});
And i get an "invalid label" error. Any ideas?
Also, a side note, I've tried the AJAX method as well:
$.ajax({
url: 'http://rockbottom.nozzlmedia.com:8000/api/portland/',
dataType: 'jsonp',
data: 'count=1',
success: function(msg){
console.log(msg)
}
});
and both give the same exact error, and both work fine with Flickr and Twitter examples, so it must be something to do with the feed, but I dont have access to the feed, but I could ask them to fix something IF it's their issue.
Make sure that the server side can handle the JSONP request properly. See here for example.
Edit: It seems that the server doesn't wrap the returned JSON object with the callback function name. The server should return:
callback( { json here } )
and not
{ json here }
That URL looks like it's expecting you to provide a JSONP callback (from the callback=? bit). That's probably the problem; it's returning Javascript rather than JSON (because that's how JSONP works). See the $.ajax docs for more about using JSONP services.
The returned content has unescaped double-quotes in one of the strings. It's invalid JSON:
..."full_content":"just voted "with Mandy " on...

Categories