Javascript and Django Rest Framework - cannot read property - javascript

I'm trying to retrieve data from an API endpoint that i created with Django Rest Framework. At first, my code worked but now i keep getting this error:
Uncaught TypeError: Cannot read property 'ticker' of undefined
It's weird, because the console.logstatement in the following code returns nothing, although i'm sure that there is data in the endpoint that i'm calling.
This is what the data i'm trying to retrieve looks like:
[
{
ticker: "TEST",
Price: 7876
}
]
And this is the Ajax function that i built:
function doPoll(){
$.getJSON('http://127.0.0.1:8000/tst/', function(data) {
console.log(data[0]);
$('#data').text(data[0].ticker + ' ' + data[0].Price);
setTimeout(doPoll, 100);
});
}
doPoll();
And this is where the data should appear:
<h3 id="data"></h3>
The function should be supposed to place my data on my html page and refresh that data every second.
http://127.0.0.1:8000/tst/ is the DRF API endpoint that i'm trying to call, from where i'm retrieving the JSON data.

you need to access data.results... this is standard DRF response format
function doPoll(){
$.getJSON('http://127.0.0.1:8000/tst/', function(data) {
var results = data.results;
console.log(results[0]);
$('#data').text(results[0].ticker + ' ' + results[0].price);
setTimeout(doPoll, 100);
});
}
doPoll();

You have a typo here data[0].Price should be data[0].price
$.getJSON('http://127.0.0.1:8000/tst/', function(data) {
if(data && data.length > 0){
console.log(data[0]);
$('#data').text(data[0].ticker + ' ' + data[0].Price);
setTimeout(doPoll, 100);
}else{
//console.log('No Data')
console.log("DATA is: ", data)
}
});
Validate that data[0] exists before accessing properties of it
The best way to debug this is to check the response in your browser dev tools
Network tab

Related

Call Wordnik API from NodeJS using Swagger

I am having problems trying to use the Wordnik API via Swagger (NodeJS).
I am trying to follow this documentation: swagger-api
The Wordnik API can be founded here: hhttp://developer.wordnik.com/docs.html#!/word/getRelatedWords_get_4
The JSON description of the Wordnik API: hhttp://developer.wordnik.com/v4/word.json
I am trying to call the GET /word.json/{word}/relatedWords method with the following parameters:
{word:"cars", useCanonical:true, relationshipTypes:"synonim", limitPerRelationshipType:10}
The Wordnik API requires authentification, according to the swagger-api documentation I have written the following code:
var Swagger = require('swagger-client');
var client = new Swagger({
url: 'http://developer.wordnik.com/v4/word.json',
success: function() {
client.word.getRelatedWords({word:"cars",useCanonical:true,relationshipTypes:"synonim",limitPerRelationshipType:10}, function(success){
console.log('succeeded and returned this object: ' + success.obj);
},
function(error) {
console.log('failed with the following: ' + error.statusText);
});
},
authorizations: {
api_key: new Swagger.ApiKeyAuthorization('api_key', 'MY_WORDNIK_API_KEY', 'query'),
}
});
My main problem is that I do not know how to write properly the code to call that method with that parameters. The code written above returns this error:
failed with the following: {"message": "unauthorized", "type":
"error"}
Any idea about how to write the code to make that call?
Two things: one, the Swagger url for Wordnik should be
http://api.wordnik.com/v4/word.json
Two, you need to use 'synonym', not 'synonim'.
I tried your code with both these changes and it works fine for me.
Also, I'm not sure why you're using Swagger.js here? It's definitely cooler, but you can call the API with request, e.g.:
request("http://api.wordnik.com:80/v4/word.json/"+'car'+"/relatedWords?useCanonical=false&relationshipTypes=synonym&limitPerRelationshipType=10&api_key=YOURKEYHERE", function (error, response, body) {
if (error || response.statusCode !== 200 || (body == "")) {
console.log(word + " had error: " + error)
return callback(error || {statusCode: response.statusCode});
}
else {
// console.log(word);
callback(null, JSON.parse(body));
}
});

UserCannotBeAlteredWithoutSessionError when updating PFUser on Parse from Heroku node.js app

I'm trying to update a PFUser in my Parse database from a node.js app running on Heroku. I'm calling the Parse cloud function from an iOS app.
Here's the part of the code I use to update the user on parse as well as creating the user on Stripe (the Stripe part works fine):
Parse.Cloud.define("createCustomerWithCreditCardToken", function(request, response) {
var userId = request.user.id;
var sourceId = request.params.creditCardToken;
var customerId;
var userSessionToken = request.user.getSessionToken();
console.log('userId: ' + userId + ' source: ' + sourceId + ' userSessionToken: ' + userSessionToken);
stripe.customers.create({
source: sourceId,
description: userId
}, function(error, customer) {
if (error !== null) {
response.error('error creating customer: ' + error);
}else {
var userQuery = new Parse.Query('User');
userQuery.equalTo('objectId', userId);
userQuery.first({sessionToken: userSessionToken}).then(function(user) {
console.log('user from parse query: ' + user.get("username"));
user.set("stripeCustomerId", customer.id);
user.save(null, {
success: function(parseCustomer) {
console.log('customer saved to parse: ' + parseCustomer);
},
error: function(error, parseCustomer) {
console.log('customer save failed: ' + JSON.stringify(error, null, 2) + ' with error: ' + JSON.stringify(parseCustomer,null, 2));
}
});
});
customerId = customer.id;
console.log('customerId: '+ customerId);
// response.success(customer);
response.success('Customer: ' + JSON.stringify(customer, null, 2) + 'error: ' + error);
}
});
});
I get the following error log output when I run this:
error log output
error: { "code": 206, "message": "Parse::UserCannotBeAlteredWithoutSessionError" }
In this post the current user concept in a node.js app context is discussed by a Parse engineer.
Also in Cloud Code, the concept of a method that returns the current
user makes sense, as it does in JavaScript on a web page, because
there’s only one active request and only one user. However in a
context like node.js, there can’t be a global current user, which
requires explicit passing of the session token.
Essentially he advises to do this:
Parse.Cloud.define('findBacon', function(req, res) {
var token = req.user.getSessionToken();
var query = new Parse.Query('Bacon');
// Pass the session token to the query
query.find({ sessionToken: token }).then( ... );
});
I have also tried using {useMasterKey:true} instead of {sessionToken:userSessionToken} which produces the same error.
I might just be missing some obvious detail, but I just can't seem to find it. Any ideas on how to solve this are greatly appreciated.
Turns out there's a third way of handling credentials:
Parse.Cloud.useMasterKey();
I placed this line in the beginning of the entire method, that did it for me. I'm not sure of the implications of giving the whole function these credentials though.
I'm not sure when you would use the other options either.
If someone comes across this and would like to elaborate, I'll be happy to give the right answer to a good explanation of when to grant which credentials.

Error in JSON when I am doing a AJAX call in jQuery

I'm getting the following error in the console when I am trying to return a string of JSON from a AJAX call.
Uncaught SyntaxError: Unexpected token
I have added a codepen with the code I am using.
If you click the convert button and look in the console you will see the error.
I cannot for the life of me figure it out.
Thanks.
JB
http://codepen.io/anon/pen/XJvyWq
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback=?", function(data){
console.log("Data: " + data);
}, 'json')
});
First remove the "=" .
for a string display in the console you can use the methode stringify of the JSON object
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback", function(data){
console.log("Data: " +JSON.stringify(data) );
}, 'json');
});
or for display an object in the console you can juste write :
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback", function(data){
console.log(data );
}, 'json');
});
the result :
Object {To: "CAD", From: "EUR", Rate: "1.3138"}
Remove json at the second parameter as #SnehalShah said and it'll work
$('.convert').click(function(){
$.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback=?", function(data){
console.log("Data: " + JSON.stringify(data));
});
});
http://jsfiddle.net/1z20m3pL/
Try this way::
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback=?", function(data){
console.log("To: " + data.To);
console.log("From: " + data.From);
console.log("Rate: " + data.Rate);
});
});
Remove the callback=? from the end of the URL you are providing OR remove the 'json' from the .get() method call.
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD", function(data){
console.log(data);
});});
This is because jQuery assumes that when you pass a "callback" parameter in URL and type 'json' that the response will be JSONP. But in this case the server sends a JSON string. Instead of passing "?" if you pass the name of an existing function the error will not be thrown.
The current response by the server is:
{"To":"CAD","From":"EUR","Rate":"1.3138"}
If the Server was responding with JSONP and if the callback you passed was "test" then the response would have been:
test({"To":"CAD","From":"EUR","Rate":"1.3138"})
http://codepen.io/tejzpr/pen/yymQNz?editors=101 explains both cases.

Parsing server response with $.parseJSON failed

I've got these two simple functions:
function getBatchSliceInfo(batch_num){
//get the batch slice info for the batch_num
alert('batch num is ' + batch_num); //returns the batch_num correctly
$.getJSON("statistics_batchdb.jsp", {batch_number: batch_num, slice_stats: 'true'}, showTable);
}
function showTable(data){
$("#table_slice_stats").hide();
if(data.error){
console.log("Something went wrong");
}
var jo = $.parseJSON(data);
alert('This JSON object has this many elements: ' + jo.length);
$.each(jo[0], function (i, val){
alert('This i value is' + i );
alert('This val value is' + val);
});
$("#table_slice_stats").show();
}
So I call getBatchSliceInfo on the click of a button and we get the JSON.
The response seems to be correct, so server side I'm alright.
However, I'm not passing that response correctly to showTable. "data" appears to be null because in the console I get the error:
Uncaught TypeError: Cannot read property 'length' of null batch_statistics_new.jsp:274
showTable batch_statistics_new.jsp:274
o jquery-1.7.2.min.js:2
p.fireWith jquery-1.7.2.min.js:2
w jquery-1.7.2.min.js:4
d jquery-1.7.2.min.js:4
I'm sure this is a very simple syntax question but I have no idea what's going on.
check your data
var data= [{slice_name:Nutrion,iteration_zero:.....},{......},{......}]
After convert to json Format.your data become like this,
var data= {[{slice_name:Nutrion,iteration_zero:.....},{......},{......}]} //It not json format.
if you tring to use length property it throwing an exceptions.so,do the same think without parsing into json.

JSON Request appended with [object%20Object] in jQuery

I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.

Categories

Resources