How to get properties from an object - javascript

I'm using this code to retrieve a simple JSON object:
function userinfo() {
var user = new Object();
$.getJSON('###', function(data){
user.id = data.user.uID;
user.name = data.user.uname;
});
return user;
}
var user = userinfo();
console.log(user);
When I run console.log on the user object outside of the function, I can see the properties of the object (id, name). But when I try to console.log "user.id" or "user.name", they come up as undefined. I can't work out why this is, or what I can do to retrieve the properties without having to iterate over them.
Any suggestions?

The AJAX call to get the JSON is asynchronous, the callback function(data) isn't called until the AJAX returns, but you are reading user right after the AJAX request is sent, but before the AJAX response is received.
Try this:
function userinfo() {
$.getJSON('###', function(data){
var user = new Object();
user.id = data.user.uID;
user.name = data.user.uname;
// Do your stuff here
console.log(user);
});
}
userinfo();
Answer to comment:
Just have a function like this on the app:
function processUser(user){
console.log(user);
}
Then use it in the AJAX callback,
$.getJSON('###', function(data){
var user = new Object();
user.id = data.user.uID;
user.name = data.user.uname;
// Do your stuff here
processUser(user);
});
#Simon, you can do usual application logic in processUser() now, e.g.:
var usersList = []; // Assume this is a global for your app
function processUser(user){
usersList.push(user);
// now other parts of your app can find this user in the list
}

function userinfo(callback) {
$.getJSON('###', function(data){
callback({
id: data.user.uId,
name: data.user.uname
});
});
}
var user;
userinfo(function(newUser) {
user = newUser;
// do work with user.
});
// execution continues here before callback returns. User will not be set.
user.name // error no property name of undefined.

Here's the fix:
function userinfo() {
var user = new Object();
$.ajax({
async: false, //solution right here
url: '/login/user.html',
success: function (data) {
user.id = data.user.uID;
user.name = data.user.uname;
}
});
return user;
}
var user = userinfo();
console.log(user.id);
Works perfectly.

Related

Parse : Retrieving properties from an object that is related

So I am doing a query to bring back a list of records, these records have a link to the user that created the record. The link is to the object.
My query gets me the object but I cant then access the fields of that object (except of course ID)
query.equalTo("search", search);
query.include("user");
query.find({
success: function(Report) {
for (var i = 0; i < Report.length; i++) {
var test = Report[i].id;
query.get(test, {
success: function(result) {
var reportDescription = result.get("reportDescription");
var reportPicture = result.get("reportPicture");
var reportPosition = result.get("reportPosition");
var reportType = result.get("reportType");
var reportDate = result.get("createdAt").toLocaleString();
var reportSearchId = result.get("search").id;
var user = result.get("user")
console.log(user)
var reportSearchBy = user.username;
},
error: function(result, error) {
alert(error.message);
}
});
};
},
error: function(error) {
alert(error.message);
}
});
What am I doing wrong?
i tried to run similar code to what you did. when i tried to access with dot notation i get undefined but when i tried to get it with .get("fieldName") it works..
here is my code:
var FileTest = Parse.Object.extend("FileTest");
var query = new Parse.Query(FileTest);
query.include("user");
query.find().then(function(results){
var lastItem = results[results.length - 1];
if (lastItem){
var user = lastItem.get("user");
console.log(user.get("username"));
}
},function(error){
});
please notice that i also use Promise for better coding and in order to get the username i did lastItem.get("username")
so please try to replace user.username with user.get("username")
and see if it works.

Taking data from a javascript object queried from parse.com

I have a parse.com database which i am querying using the objectID. It returns the data but I can only see it inside the promise object as an attribute, i can't figure out how this works from the documentation, how should i actually get the data and turn it into an object rather than a Promise. Should i call the function after or save it as a variable or something in the success function, do i need to define review somewhere earlier? any example would be awesome
var query = new Parse.Query("business_and_reviews");
var results = new Parse.Object("business_and_reviews");
query.get("pLaARFh2gD", {
success: function(results) {
// results is an array of Parse.Object.
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
var name = results.get("city");
console.log(name);
This is the Promise in chrome
get() returns only one object with the id.
var query = new Parse.Query("business_and_reviews");
query.get("pLaARFh2gD", {
success: function(result) {
var name = result.get("city");
console.log(name);
}
});
Here is another example from the document.
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("xWMyZ4YEGZ", {
success: function(gameScore) {
var score = gameScore.get("score");
var playerName = gameScore.get("playerName");
var cheatMode = gameScore.get("cheatMode");
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
Thanks, I solved it now, first had to be inside the success: function, then had to select the info in the object as follows:
var query = new Parse.Query("business_and_reviews");
var results = new Parse.Object("business_and_reviews");
query.get("pLaARFh2gD", {
success: function(results) {
console.log(results["attributes"]["city"]);
},
error: function(object, error) {
}
});

Parse Cloud Code save() doesn't seem to save a field

I'm trying to run save() on a retrieved _User object, but it doesn't seems to save the field I've modified ("ignoredUsers"), which is an array. Although I can see that the save actually went through, as updatedAt does change.
Here is the code:
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", userid1);
query.first({
success: function(result){
var ignored = result.get("ignoredUsers");
if (!ignored) {
ignored = [];
}
ignored.push(userid2);
result.set("ignoredUsers", ignored);
result.save();
}
});
function appendUser(toUser, userId) {
return toUser.fetch({
success: function(user) {
var ignored = user.get("ignoredUsers");
if (!ignored) {
ignored = [];
}
ignored.push(userId);
user.set("ignoredUsers", ignored);
user.save();
}
});
}
Parse.Cloud.job("ignoredUsers", function(request, status) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query("Conversation");
return query.each(function(conversation) {
var participants = conversation.get("participants");
var userid1 = participants[0].id;
var userid2 = participants[1].id;
var user1 = participants[0];
var user2 = participants[1];
return appendUser(user1, userid2).then(function() {
return appendUser(user2, userid1); });
});
status.success();
});
The problem was that the cloud function returned before waiting for the callbacks to finish

Updating outside variables inside a javascript function in Node.js

I am developing a NodeJS application and encountered following problem:
I am using node module node-rest-client to issue REST requests using an API. I use post method provided by the module for my purpose. I need to fetch the json response and write it to seperate variables and return them.
I have defined returnData variable outside the client.post method. I need to update this returnData variable inside the function which is passed as a parameter to the client.post method.
But I have a scope issue here. Although I try to update the returnData variable inside that function, when execution returns from client.post function, I see that the same values I have set (in this case null, but may be any value) before calling client.post function still persists in the variable.
How can I define scope well so that I can update an outside variable inside the function which I pass as a parameter to another function? Any help would be greatly appreciated.
Following is my Code:
module.exports = function(){
require("../config");
var restClient = require('node-rest-client').Client;
var client = new restClient();
var sessionID = null,
reqID = 1;
var login = function(username, password){
var requestParams = {};
var apiParams = {};
requestParams.jsonrpc = "2.0";
requestParams.method = ZABBIX_API_METHODS.login;
apiParams.user = username;
apiParams.password = password;
requestParams.params = apiParams;
requestParams.id = reqID;
requestParams.auth = null;
var args = {
data: requestParams,
headers:{"Content-Type": "application/json-rpc"} // ask response type to be application/json-rpc
};
var returnData = {};
returnData.status = null;
returnData.data = null
client.post(ZABBIX_API, args, function(resData,rawRes){
if(rawRes.statusCode == 200){
returnData.status = rawRes.statusCode;
returnData.data = resData;
}
else{
returnData.status = rawRes.statusCode;
returnData.data = "Request Failed!";
}
reqID = reqID + 1;
console.log(returnData.data);
});
console.log("SessionID:"+getSessionID());
return returnData;
}
var functions = {
login: login
}
return functions;
}
Thank you.
.post is Async, you should do it like this,
var login = function(username, password, callback){
..................
client.post(ZABBIX_API, args, function(resData,rawRes){
if(rawRes.statusCode == 200){
returnData.status = rawRes.statusCode;
returnData.data = resData;
}
else{
returnData.status = rawRes.statusCode;
returnData.data = "Request Failed!";
}
reqID = reqID + 1;
return {login: returnData};
});
//remove all below return statements

Uncaught TypeError: Object has no method ... Javascript

I'm having an issue where I get an error that says...
"Uncaught TypeError: Object f771b328ab06 has no method 'addLocation'"
I'm really not sure what's causing this. The 'f771b328ab06' is a user ID in the error. I can add a new user and prevent users from being duplicated, but when I try to add their location to the list, I get this error.
Does anybody see what's going wrong? The error occurs in the else statement of the initialize function as well (if the user ID exists, just append the location and do not create a new user). I have some notes in the code, and I'm pretty sure that this is partly due to how I have modified an example provided by another user.
function User(id) {
this.id = id;
this.locations = [];
this.getId = function() {
return this.id;
};
this.addLocation = function(latitude, longitude) {
this.locations[this.locations.length] = new google.maps.LatLng(latitude, longitude);
alert("User ID:" );
};
this.lastLocation = function() {
return this.locations[this.locations.length - 1];
};
this.removeLastLocation = function() {
return this.locations.pop();
};
}
function Users() {
this.users = {};
//this.generateId = function() { //I have omitted this section since I send
//return Math.random(); //an ID from the Android app. This is part of
//}; //the problem.
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
this.getUser = function(id) {
return this.users[id];
};
this.removeUser = function(id) {
var user = this.getUser(id);
delete this.users[id];
return user;
};
}
var users = new Users();
function initialize() {
alert("Start");
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data){
var user_id = data[0];
var latitude = data[1];
var longitude = data[2];
if (typeof users.users[user_id] === 'undefined') {
users.createUser(user_id);
users.users[user_id] = "1";
user_id.addLocation(latitude, longitude); // this is where the error occurs
}
else {
user_id.addLocation(latitude, longitude); //here too
alert(latitude);
}
}
})
}
setInterval(initialize, 1000);
Since I get the ID from the phone and do not need to generate it here (only receive it), I commented out the part that creates the random ID. In doing this, I had to add a parameter to the createUser method within Users() so that I can pass the ID as an argument from Initialize(). See the changes to createUser below:
Before, with the generated ID (the part where the number is generated is in the above code block with comments):
this.createUser = function() {
var id = this.generateId();
this.users[id] = new User(id);
return this.users[id];
};
After, with the ID passed as an argument:
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
If anyone has any suggestions I would really appreciate it. Thanks!
Here you're getting user_id by :
var user_id = data[0];
So it's a part of the json answer : maybe a string or another dictionnary, this can't be a user object. You should try to update your code in your success function inside the "if" block by :
user = users.createUser(user_id);
//The following line is a non sense for me you put an int inside
//an internal structure of your class that should contain object
//users.users[user_id] = "1";
user.addLocation(latitude, longitude);

Categories

Resources