I'm getting a malformed JSON response from an AJAX $.getJSON() request. I don't understand the problem.
Here is the request code:
var myfunc = function(){
$.getJSON( "/", {"data": ""}, function( data, status ){
var values = data;
$("#temperature").html( values.temperature.toFixed(1).toString() );
$("#humidity").html( values.humidity.toFixed(0).toString() );
});
});
and here is the JSON data received (extracted via Firefox debugger):
{
"temperature": 17.799999237060547,
"humidity": 35.900001525878906,
"failed": false
}
I cannot see what is malformed here. And the code works. DOM elements id="temperature" and id="humidity" are updated correctly.
I got exactly the same result using $.get() with JSON.parse().
Does anybody have an idea how to solve the problem?
My guess is that the json data you are receiving over the network is malformed, but, it is successfully converted to an object anyway.
getJSON automatically applies JSON.parse(..) on the received data.
Try using the 'network' listener tab on Google Chrome to see exactly the response you are receiving BEFORE it is parsed. There might be a missing " or something like that.
If you have access to the server code, you could also try logging the response in there.
edit:
you might be interested by this link
Might have to do with some server config.
Mimetype is also mentionned in this link.
So I am working on something that would allow me to read JSON data from an outside server, and print it out in a more human-readable format. So far I have this:
var address = "example.com";
//not the actual site
$.ajax({
url: address,
dataType: "JSONP",
success: function(data)
{
var obj = JSON.parse(data);
//Misc printing code goes here
},
error: alert("Error")
});
However, I am consistently receiving the error alert.
The console tells me "Unexpected token &". Looking at a few other sources, the issue seems to be that the actual data present on the site is nothing more than raw text.
I changed the dataType field to "text" to try and fix this, but the console error instead changed to tell me that I wasn't allowed access.
I tried retrieving the data and treating it as text with "JSONP text", but it simply returned to the previous "Unexpected token &" error.
Is there any way I can receive text data from an outside server? If not, is there some workaround I could use, such as saving the data to a document and importing it into my code from there?
I'm using the Yummly API (https://developer.yummly.com/documentation) and I am trying to parse a JSONP list of courses to use in a drop-down box. The format of the file I am requesting (located at http://api.yummly.com/v1/api/metadata/course?_app_id=[My App ID]&_app_key=[My App Key]) is:
set_metadata('course', [{"id":"course-Main Dishes","type":"course","description":"Main Dishes","searchValue":"course^course-Main Dishes"},....................}])
The request seems to work fine, and I can view the results in the Network tab in Chrome. However, in the console I get the error "Uncaught ReferenceError: set_metadata is not defined" I've done a lot of looking around, and have found people with similar but different errors, but I have not understood the cause or why the fixes for their errors work. I am fairly new to jQuery, so I'm guessing I'm doing something wrong with my request, which is:
var coursesURL = 'http://api.yummly.com/v1/api/metadata/course?_app_id=' + appID + '&_app_key=' + appKey;
var courses = [];
//Query for the list
$.getJSON(coursesURL + '?callback=?', null, function(data) {
console.log(data);
//Go through each result object found
$.each(data.course, function(i, course) {
courses.push(course.description);
});
console.log(courses);
});
Any help is greatly appreciated. I would also really appreciate an explanation of what I am missing, not just the fix. Thank you.
The reasons I'm adding this as an answer and not a comment are because i don't have enough reputation to comment and this is the only thing i can find on the yummly api returning jsonp.
I was able to get past the "uncaught referenceError" problem but now its only returning the word 'allergy', which is in the response, and I'm not getting the rest of the data.
here is my code:
$.ajax({
url:"//api.yummly.com/v1/api/metadata/allergy?_app_id=[APP_ID]&_app_key=[APP_KEY]?callback=",
dataType:"jsonp",
jsonpCallback:"set_metadata",
beforeSend:function(){
console.log("sending");
},
success: function (data){
console.log(data);
},
error: function(data){
console.log("send error and returned:");
console.log(data);
}
});
here is the response:
set_metadata('allergy', [
{"id":"392","shortDescription":"Wheat-Free","longDescription":"Wheat-Free","searchValue":"392^Wheat-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"393","shortDescription":"Gluten-Free","longDescription":"Gluten-Free","searchValue":"393^Gluten-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"394","shortDescription":"Peanut-Free","longDescription":"Peanut-Free","searchValue":"394^Peanut-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"395","shortDescription":"Tree Nut-Free","longDescription":"Tree Nut-Free","searchValue":"395^Tree Nut-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"396","shortDescription":"Dairy-Free","longDescription":"Dairy-Free","searchValue":"396^Dairy-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"397","shortDescription":"Egg-Free","longDescription":"Egg-Free","searchValue":"397^Egg-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"398","shortDescription":"Seafood-Free","longDescription":"Seafood-Free","searchValue":"398^Seafood-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"399","shortDescription":"Sesame-Free","longDescription":"Sesame-Free","searchValue":"399^Sesame-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"400","shortDescription":"Soy-Free","longDescription":"Soy-Free","searchValue":"400^Soy-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"401","shortDescription":"Sulfite-Free","longDescription":"Sulfite-Free","searchValue":"401^Sulfite-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]}
]);
the line of code that says:
jsonpCallback:"set_metadata",
in the ajax call gets me past the reference error but im not getting the rest of the data that's in the response.
please help?
Finbar
I figured out the problem.
JSONP is returning not JSON text, but a function to the callback. Thus, I needed a function in my code called "set_metadata" that is used upon success of the json/ajax call.
Specifically, I defined function
function set_metadata(course, data) {
//Do stuff here
};
I tested it and that correctly captures the data I am trying to get.
I'm trying to perform a xquery and get its result, with the following code:
$.get('http://localhost:8984/rest/lod?query=/*:teiCorpus//*:TEI',
function(data) {
alert(data);
});
I was expecting a xml response, but so far I don't get a thing.
Firebug display the following error:
XML Parsing Error: no element found Location: moz-nullprincipal:{a9dddfb7-5488-424b-8ab1-76913e889282} Line Number 1, Column 1: ^
I don't understand what I'm doing wrong.
Any ideas?
EDIT:
When I place:
http://localhost:8984/rest/lod?query=/*:teiCorpus//*:TEI
in my address bar, I get
<TEI xmlns="http://www.tei-c.org/ns/1.0" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:svg="http://www.w3.org/2000/svg">
<teiHeader type="text" xml:id="Fr1">teiHeader</teiHeader>
<text>teiText</text>
</TEI>
and that's exactly what I need to retrieve with the get.
It looks like your URL has some illegal characters, try this
$.get('http://localhost:8984/rest/lod',{ query: '/*:teiCorpus//*:TEI' },
function(data) {
alert(data);
});
putting it in as the data parameter will hopefully escape the illegal characters
EDIT:
Looking into your problem more - there could be 2 more things it could be:
1 ) Your trying to do a cross domain request - this is not allowed with XML (you can determine this by looking at the URL in your browser, if it's not the same as http://localhost:8984 its cross-domain)
2 ) Your xml response you are returning is incorrect
what I need to do is read the content of a "public" google spreadsheet (by public I mean that I saved the sheet clicking on "File > Publish to the web", so it's accessible without the need to be logged in into a google account), and, why not, write something into it too.
googlin' around, I found that I can access the sheet and get the xml equivalent of the sheet content with something like
https://spreadsheets.google.com/feeds/list/<sheetCode>/od6/public/values
It works great if I load that url into a browser. But I need to find a "javascript-way" to get and handle the returned value, ie the xml (or json, but xml would be preferable).
I tried to use an ajax call, but I think there's something messy with the protocol.. I can't get the server response correctly.
$.ajax({
type: "GET",
url: "https://spreadsheets.google.com/feeds/list/<sheetCode>/od6/public/values",
success: function(data){alert("yeah");},
error: function(){alert("fail..");},
dataType:"xml",
});
I also tried to get the json instead of xml, adding "?alt=json" to the url and changing the datatype, but I still have the problem..
Any idea / suggestion?
Thanks in advance, best regards
You need to request with a JSONP call and you need to specifiy a callback - method. This can be done in jQuery using:
var url = 'https://spreadsheets.google.com/feeds/list/<CODE>/od6/public/values?alt=json-in-script&callback=?';
jQuery.getJSON(url).success(function(data) {
console.log(data);
}).error(function(message) {
console.error('error' + message);
}).complete(function() {
console.log('completed!');
});
Documentation and samples for google spreedsheets .