I am receiving the following valid JSON from my server:
[{"name":"Bubble Witch Saga 2","impressions":10749},{"name":"Grinder","impressions":11284},{"name":"Loovoo","impressions":12336},{"name":"Injustice God Among Us","impressions":12786},{"name":"Bookmyshow","impressions":13182},{"name":"Angry Bird","impressions":15404},{"name":"Flipkart","impressions":16856},{"name":"CNN-IBN","impressions":17230},{"name":"Fore Square","impressions":17595},{"name":"NDTV","impressions":19542},{"name":"Whatsapp","impressions":19976}]
But I keep getting an error in my console saying "JSON.parse: unexpected character." This is my client-side code:
$.ajax({
'type': 'get',
'data': {},
'dataType': 'json',
'url': 'dashboard/data/'+type,
'complete': function(data) {
var top10Value = JSON.parse(data);
$.each(top10Value, function(key,value){
console.log(key+" -- "+value);
});
}
});
Why am I getting this error?
When you specify dataType : json, result is already parsed in jQuery.
Moreover, complete
function argument is returning an object representing the result not the result itself.
That case you should use var top10Value = JSON.parse(data.responseText);
jQuery is clever enough to parse the response as it is, even if dataType isn't specified.
In your case, it is specified and therefore, it is already parsed and data is the parsed JSON object.
What you are doing is therefore parsing an Object.
Doc says:
dataType: (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the
server. If none is specified, jQuery will try to infer it based on the
MIME type of the response (an XML MIME type will yield XML, in 1.4
JSON will yield a JavaScript object, in 1.4 script will execute the
script, and anything else will be returned as a string). The available
types (and the result passed as the first argument to your success
callback) are:
data returned already json format only,
$.ajax({
'type': 'get',
'data': {},
'dataType': 'json',//Return Json Format
'url': 'dashboard/data/',
'complete': function(data) {
//data returned already json format only
//var top10Value = JSON.parse(data);
$.each(top10Value, function(key,value){
console.log(key+" -- "+value);
});
}
});
Related
I am trying to take a typical jQuery AJAX call and wrap it in its own function so I can call it with different parameters to make it more dynamic. I seem to be missing something about the success or with callbacks in general. The basic function is to pass JSON to a Google charts implementation. This works if I hardcode the JSON but I want to pick it up out of my REST API. Right now I have this small bit of code:
var getAjax = function (url){
$.ajax({
url: url,
dataType: json,
success: drawChart
});
}
var drawChart = function (data) {
jsonData = data;
console.log(jsonData);
// Create our data table out of JSON data loaded from server.
var jsonDataTable = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
//var chartPie = new google.visualization.PieChart(document.getElementById('pie'));
//var chartBar = new google.visualization.BarChart(document.getElementById('bar'));
var chartJson = new google.visualization.BarChart(document.getElementById('json'));
//chartPie.draw(trailerData);
//chartBar.draw(chewyData);
chartJson.draw(jsonDataTable);
}
console.log('got here');
getAjax("data/dashboard0");
When I check the console I can see a 200 from jQuery but I get nothing in my window. I also tried using the getAjax(data) to define the function but in my reading I saw I should do it like this but I am not quite sure which approach is the correct one.
I imagine your syntax error is preventing the code from working...
The dataType should be a string:
dataType: 'json',
Note on response data - If you need the raw data, rather than a parsed data object, you can get that from the raw XHR... no need to unwind the parsed data into another string.
var drawChart = function (data, status, jqXHR) {
var jsonString = jqXHR.responseText;
var parsedData = data;
//...
You should instead return a promise in your function, then resolve it via .then(). success: drawChart is not very dynamic. Observe the following...
var getAjax = function (url){
return $.ajax({ url: url, dataType: 'json' });
}
[...]
getAjax('data/dashboard0').then(function(response) {
// callback - do drawing tuff
});
console.log('got here before callback')
Check out the jQuery deferred docs for more information
The success's method first argument is parsed. If you need a JSON string then you have to JSON.stringify(responseData) which will return a JSON string.
Even if you set dataType: 'json', jQuery will still parse the response.
Please read the jQuery Docs for dataType:
dataType: "json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests are converted to "jsonp" unless
the request includes jsonp: false in its request options. The JSON
data is parsed in a strict manner; any malformed JSON is rejected and
a parse error is thrown. As of jQuery 1.9, an empty response is also
rejected; the server should return a response of null or {} instead.
(See json.org for more information on proper JSON formatting.)
I am trying to send a Django HttpResponse encoded as JSON to Javascript.
Python:
response_data = {}
response_data['status'] = 'incomplete'
return HttpResponse(json.dumps(response_data), content_type="application/json")
Jquery:
function auth_request(){
$.ajax({
url: AUTH_ENDPOINT + "myid0001",
context: document.body,
success: function(response){
console.log(response);
console.log(response.status);
if(response.status == "incomplete"){
//do something here
}
}
}
});
}
The console prints {"status": "incomplete"} for the first console log and undefined for the console.log function accessing the status element.
I tried using JSON.parse(response) but I get the error
Uncaught SyntaxError: Unexpected token a in the jquery.js file which I believe is indicating that the object is already a JSON object. However, if I check the type of the object, it displays string. How can I access the elements of the response JSON object?
You need to parse the Json back into a JS object when it's received. Otherwise, it's just text.
jQuery will do that for you if you specify dataType: "json" in the Ajax call.
I found the solution. It turns out that my Django setup was returning some additional string items so when I tried to set dataType: "json" (as #Daniel Roseman suggested) or in the jQuery function or use JSON.parse(response) I received an error. I was able to remove the extra string and it worked properly.
When trying to retrieve a playlist using the YouTube developers API v2, I continually get a response in the Chrome console that the loaded file is the wrong type, and is a Document, not XML. Here is the code I am using:
$.get('https://gdata.youtube.com/feeds/api/playlists/8BCDD04DE8F771B2?v=2',
function(data)
{
var doc = data;
console.log( data );
});
The result in the console is: #document where I am expecting the result to be an XML doc.
it's ok, it's is xml, this is xml representation by jquery
you can use xml2json
You sure are getting an xml document from the feed, and if you want to be sure that your jQuery ajax request is recognizing it as such you can specify the "dataType" parameter also like so:
$.get('https://gdata.youtube.com/feeds/api/playlists/8BCDD04DE8F771B2?v=2',
function(data)
{
console.log( 'An xml feed is being retrieved, true or false:'+($(data).children('feed').length == 1).toString());
},'xml');
or using the longhand $.ajax method, which can help in debugging by using the "error" option as well:
$.ajax({
url: 'https://gdata.youtube.com/feeds/api/playlists/8BCDD04DE8F771B2?v=2',
dataType: 'xml',
success: function(data){
console.log( 'An xml feed is being retrieved, true or false:'+($(data).children('feed').length == 1).toString());
},
error: function(xhr,stat,err){ console.log(stat+': '+err); }
});
Here is an example using the $.ajax method, and indeed it is being recognized as valid xml without even specifying the dataType parameter: http://jsfiddle.net/UZddq/2/
It may be easier to work with json also. You can retrieve the feed from youtube in json format by specifying the "alt" parameter in the url:
$.ajax({
url: 'https://gdata.youtube.com/feeds/api/playlists/8BCDD04DE8F771B2?v=2&alt=json',
dataType: 'json',
success: function(data){
console.log( 'A json feed is being retrieved, true or false:'+data.hasOwnProperty('feed').toString());
},
error: function(xhr,stat,err){ console.log(stat+': '+err); }
});
Here is the json version example: http://jsfiddle.net/hvFQj/2/
var url = "/MyApp/pspace/filter";
var data = JSON.stringify(myData);
$.post(
url,
data,
function(response, textStatus, jqXHR) {
console.log("response: " + response);
},
"json"
);
In reality, response should be a json string.
In Chrome, response is a string that I can parse with $.parseJSON().
In Firefox, response is an XMLDocument (with a parse error), unless I use dataType: "text". Why?
If you are setting "json" as your response type jQuery should parse it into an object for you automatically. If you forgot to tell jQuery what type of response to expect different browsers will treat it differently.
The solution is to make sure you specify your response type as "json" and then of course to make sure the data that is being returned is an actual JSON string.
I have a problem accessing JSON data. I'm new to JSON and jquery so there is probably a easy solution to it and I would be glad to find out.
My jQuery:
$.post(
"currentPage.php",
{
'currentPage': 1
},
function(data){
$("body").append(data);
}
);
currentPage.php:
$returnArray['left'] = 'test_left';
$returnArray['right'] = 'test_right';
$returnArray['numLeft'][] = 1;
$returnArray['numRight'][] = 2;
$returnArray['numRight'][] = 3;
print json_encode($returnArray);
I tried to access the data like this:
data.left
data['left']
but it returns blank, how is the best way to access the data in the HTML-file?
I could be wrong, but I don't think the post method assumes a data return-type of json. You could set that by changing the ajax function to:
$.post(
"currentPage.php",
{
'currentPage': 1
},
function(data){
$("body").append(data);
},
"json"
);
Provide the datatype you expect to get as parameter to the .post() method (in your case json):
$.post("currentPage.php",{'currentPage': 1},
function(data){
$("body").append(data);
},
'json' // <-- add the expected datatype
);
I think the default is to treat the result as HTML. Read the documentation.
jQuery.post( url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ] )
urlA string containing the URL to which the request is sent.
dataA map or string that is sent to the server with the request.
success(data, textStatus, XMLHttpRequest) A callback function that is executed if the request succeeds.
dataType The type of data expected from the server.
In JQuery, you need to set the return data type (dataType) to json so the function knows what type of data to expect and process. From the manual:
"json": Evaluates the response as JSON
and returns a JavaScript object. In
jQuery 1.4 the JSON data is parsed in
a strict manner; any malformed JSON is
rejected and a parse error is thrown.
(See json.org for more information on
proper JSON formatting.)
You can do this with the full $.ajax() call, or you can use $.getJSON(). There is no HTTP POST shortcut to return JSON (i.e. $.postJSON doesn't exist), but you can supply the dataType parameter to $.ajax() or just add the parameter to $.post() . When you have a JSON object, use json.keyName to access the data.
$.ajax({
url: "currentPage.php",
data: {
'currentPage': 1
},
dataType: "json",
type: "post",
success: function(data) {
$("body").append(data);
}
});