Incorrect user profile picture being displayed from JS array - How to address this? - javascript

Sorry for the long post, but I'm not sure the issue comes across without all the code.
I'm using parse.com and the JavaScript SDK.
The below code is part of my users profile page, it displays their profile picture to them on screen and allows them to change it.
Changing the profile picture works fine and is uploaded as expected. The issue is that on the profile page the profile is taking the first users picture and displaying it on page for any user. Basically its not looking at the current user.
I think that I need to update the query to include something like var currentUser = Parse.User.current(); and introduce it into my code. Whatever why I try and do this I'm hitting a brick wall. Any help would be great
I'm struggling if this is the case to understand how to change my code to avoid this happening?
/////////////////////////Queries the users profile picture and shows on page////////////////////////
var UserProfilePic = Parse.Object.extend("_User");
var query = new Parse.Query(UserProfilePic);
query.exists("ProfilePic");
query.find({
success: function(results) {
// If the query is successful, store each image URL in an array of image URL's
imageURLs = [];
for (var i = 0; i < results.length; i++) {
var object = results[i];
imageURLs.push(object.get('ProfilePic').url());
}
// If the imageURLs array has items in it, set the src of an IMG element to the first URL in the array
if (imageURLs.length > 0) {
$('#profile_pic').attr('src', imageURLs[0]);
}
$('#Image01').attr('src', imageURLs[0]); //first image
},
error: function(error) {
// If the query is unsuccessful, report any errors
alert("Error: " + error.code + " " + error.message);
}
});
///////// Saves the users profile image and fields after the #save button is clicked//////
var profileSave = Parse.User.current();
function ProfileSave() {
var User = Parse.Object.extend("_User");
var profileSave = Parse.User.current();
var saveusername = $('#username').val();
var saveemail = $('#email').val();
var savegender = $('#gender').val();
profileSave.set("username", saveusername);
profileSave.set("email", saveemail);
profileSave.set("gender", savegender);
profileSave.save(null, {
success: function(profileSave) {
profileSave.save();
console.log("DONE");
alert("Profile Saved");
},
error: function(profileSave, error) {
// Fail
}
});
}
///////////////Allows the user to upload a profile image and store///////////////////////
$(document).ready(function() {
var parseAPPID = "XXXXXX";
var parseJSID = "XXXXXX";
//Initialize Parse
Parse.initialize(parseAPPID, parseJSID);
$("#fileUploadBtn").on("click", function(e) {
var fileUploadControl = $("#fileUploader")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = file.name;
console.log("here goes nothing...");
var parseFile = new Parse.File(name, file);
parseFile.save().then(function() {
console.log("Worked!");
console.dir(arguments);
var User = Parse.Object.extend("_User");
var jobApplication = Parse.User.current();
jobApplication.set("ProfilePic", parseFile);
jobApplication.save();
var profilePhoto = jobApplication.get("ProfilePic");
console.log("Done");
//jobApplication.get("ProfilePic").url;
}, function(error) {
console.log("Error");
console.dir(error);
});
}
});
});

Just found this in the featured/bounties, even though I answered it here for you, so here's my copy/pasted answer:
You're not using query.exists() the way you think you are. Also, are you just trying to check to see if the current user has a profile image? Because you can just use the .has("key") method of objects, and a user is an object. If this is in cloud code, rather than client code, you may have to fetch the user first. If it is client code, you should already have an up to date user.
You should not be extending the user object. Not necessary at all. Use the Parse.User object type, so if you're querying for users, do var query = new Parse.Query( Parse.User );
So I think what you want is something more like:
var user = Parse.User.current();
if( user.has("ProfilePic") )
{
//Do your stuff with the image
var imageURL = user.get("ProfilePic").url();
$('#Image01').attr('src', imageURL);
}
else
{
alert("Error: User does not have a 'ProfilePic' set");
}
The way your code is set up, you're just querying through all the users with profilePics and taking the first one. My code only gets the profilePic of the current user.

Related

JavaScript Class Objects not returning value

I've been working with the Microsoft Bot Framework to create a bot that can interface between MS Teams and AWS. I've been trying to write some JS functions but have been unsuccessful in getting them to operate how I want them to.
Here is what I am currently working on and am stuck on:
I am creating a 'ping' like functionality so a bot user can ping an instance in AWS and receive its status whether its running and has passed the system checks or not. My code is currently able to take the user request for the ping, retrieve the information from AWS, and can even print that info to the console. However, when I am trying to retrieve that information back out of the object that I set it to and print it to MS Teams, it says my variable is undefined.
Some code snippets are below:
class aws_Link {
constructor (mT, ping_1, i_state, i_status) {
this.myTag = mT;
this.ping = ping_1;
this.instance_state = i_state; // I declare this here, but should I?
this.instance_status = i_status; // I declare this here, but should I?
}
//i_state and i_status are just passed NULL when the object is initialized
//so they would be holding some value, not sure if I have to do this
api_link () {
var mainLink = API_LINK_TAKEN_OUT_FOR_OBVIOUS_REASONS;
var myTagFill = "myTag=";
var ampersand = "&";
var pingFill = "ping=";
var completeLink = String(mainLink + myTagFill + this.myTag + ampersand + pingFill + this.ping);
var finalLink = completeLink;
finalLink = finalLink.split(' ').join('');
//set up API-key authenticication
var options = {
url: finalLink,
headers: {
'x-api-key': 'AWS-PRIVATE-TOKEN'
}
};
if(this.ping == "TRUE") { // if the user wants to use /ping
var res = request(options, function(error, response, body) {
console.log("PING REQUEST"); //debug
body = JSON.parse(body);
var h_state = body['instanceState'];
var h_status = body['instanceStatus'];
this.instance_state = h_state;
this.instance_status = h_status;
console.log("STATE: " + h_state); //debug
console.log("STATUS: " + h_status); //debug
});
}
}
pingFunction () {
var tmp = "Instance State: " + this.instance_state + " Instance Status: " + this.instance_status;
return tmp;
}
}
And here is where I call the api_link() function and pingFunction():
var apiLink1 = new aws_Link("MY_TAG_VALUE", "TRUE", "NULL", "NULL");
var completeAPILink = apiLink1.api_link();
session.send('Request complete.');
session.send("PING: " + apiLink1.pingFunction());
So essentially the user enters in some info which gets passed to where I create the "new aws_Link" which then a my understanding is, creates an object called apiLink1. From there, it makes the request to AWS in my api_link() function, which retrieves the info I want. I thought I was then saving this info when I do the: this.instance_state = h_state; & this.instance_status = h_status;. So then when I call pingFunction() again on apiLink1, I thought I would be able to retrieve the information back out using this.instance_state and this.instance_status, but all it prints out is undefined. Any clarification on why my current code isn't working and any changes or improvements I can make would be greatly appreciated.
Thanks!

Facebook get random friends photo and name

i am using the code bellow to get a random friend from user and everything works great.. I need to implement this and i need and the name of this user.
The problem is that while friends photo is ok, the name is different from the friend's photo. It's random.
My code:
function getFriendRandom(cb) {
FB.api('/me/friends',{
fields: 'name,id,picture.width(400).height(400)'
}, function (response) {
if (response && !response.error) {
var random = Math.floor(Math.random()*response.data.length);
var thefrienam = response.data.length;
cb(response.data[random].picture.data.url + "|" + response.data[random].name);
}
});
}
And usage:
getFriendRandom(function(image){
var the_string = image;
var parts = the_string.split('|', 2);
var fimagef = parts[0];
var yourfriendsname = parts[1];
});
any idea please how to get the correct name of each random friend?

Not able to save a custom class object in Parse

I am trying to create a Customer class object which has a one to one relation with the User class. But the object doesn't save without giving any error.
Here is my code:
Parse.Cloud.afterSave(Parse.User, function(request) {
user = request.object;
role_name = user.get("role_name");
user_name = user.get("user_name");
user_id = user.get("objectId");
if (role_name == "customer"){
user = request.object;
console.log(" I am inside if else");
var Customer = Parse.Object.extend("Customer");
var cus = new Customer();
cus.set("name2" , "albert")
var relation = cus.relation("userId");
relation.add(user);
cus.save(); // Customer object should get saved here
cus.save(null, {
success: function(cus) {
// Execute any logic that should take place after the object is saved.
console.log("I am working")
alert('New object created with objectId: ' + cus.objectId);
},
error: function(error) {
// handleParseError(error);
console.log(error)
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
}
});
Log when I run this:
after_save triggered for _User for user qu808uKOgt:
Input: {"object":{"createdAt":"2015-10-11T18:36:07.661Z","objectId":"qu808uKOgt","phone":"5678956475","role_name":"customer","updatedAt":"2015-10-11T18:36:07.661Z","username":"newuser16"}}
Result: Success
I am inside if else
{"name2":"apple","userId":{"__op":"AddRelation","objects": [{"__type":"Pointer","className":"_User","objectId":"qu808uKOgt"}]}}
I fixed this bug by creating a new cloud function, which will be called immediately after the user sign's up.
Parse.Cloud.define('functionName', function(request, response){
var currentUser = Parse.User.current();
var role_name = currentUser.get("role_name");
if (role_name == "customer"){
// Do something
}
else if (role_name == "service_provider"){
// Do something else
}
)};

Why am I only being returned 3 images instead of the correct amount?

I am currently, trying to National Library of Australia's API to find pictures on a specific search term. Trove API I have the following functions which should send a query from an input form to the api and receive images back, however I am not receiving the majority of the images. In a particular example, if is search for 'sydney' I am only receiving 3 images back when there is in fact way more. For instance, this is the json, that is returned. I know that you will not be familiar with this api, but in my code below, is there anything that you can see, that would be causing it not to return all the images? I have changed a few things around to try and find the problem as well as put a few console.log statements but it is still not being kind to me.
var availableImages = {
"nla": {
"numImages":0,
"url_pattern":"nla.gov.au",
"images":[]
},
};
var url_patterns = ["nla.gov.au"];
$(document).ready(function(){
$("form#searchTrove").submit();
$("form#searchTrove").submit(function() {
resetImageData();
//get input values
var searchTerm = $("#searchTerm").val().trim();
searchTerm = searchTerm.replace(/ /g,"%20");
var sortBy = $("#sortBy").val();
//create searh query
var url = "http://api.trove.nla.gov.au/result?key="
+ apiKey + "&l-availability=y%2Ff&encoding=json&zone=picture"
+ "&sortby=relevance&n=100&q=" + searchTerm + "&callback=?";
//print JSON object
console.log(url);
//get the JSON information we need to display the images
$.getJSON(url, function(data) {
$('#output').empty();
$.each(data.response.zone[0].records.work, processImages);
//console.log(data);
printImages();
});
});
});
function processImages(index, troveItem){
console.log("av"+ availableImages);
for(var i in availableImages){
//console.log(availableImages[i].url_pattern)
if(troveItem.identifier[0].value.indexOf(availableImages[i].url_pattern) >= 0){
console.log("Trove URL "+troveItem.identifier[0].value+" Pattern: "+availableImages[i]["url_pattern"]);
availableImages[i].numImages++;
availableImages.totalimages++;
availableImages[i]["images"].push(troveItem.identifier[0].value);
}
}
}
function printImages(){
$("#output").append("<h3>Image Search Results</h3>");
for(var i in availableImages){
if(availableImages[i]["url_pattern"]=="nla.gov.au" && availableImages[i]["numImages"]>0){
printNLAImages();
console.log(availableImages);
}
}
}
function printNLAImages(){
$("#output").append("<h3>National Library of Australia</h3><p>"
+availableImages["nla"]["numImages"]+" images found from <a href='http://"
+availableImages["nla"]["url_pattern"]+"'>"
+availableImages["nla"]["url_pattern"]+"</a></p>");
for (var i in availableImages["nla"]["images"]){
$("#output").append("<img src='"+availableImages["nla"]["images"][i]+"-v'>");
}
console.log(availableImages);
}
function resetImageData(){
availableImages.totalimages = 0;
for (var i in availableImages){
availableImages[i].numImages = 0;
availableImages[i]["images"] = [];
}
console.log(availableImages); //displaying hee
}

javascript - get items with query and match items to a user who has favorited item

I am writing a script on parse.com's javascript cloud code SDK. Here is the information I have saved in my parse.com account and what I am trying to do with it.
I have a bunch of items saved in a parse class called TestItem, theses items have an objectId, item name, meal time (lunch, dinner) and a location for there columns. I also have a class called UserFavourites. In this class the objects have an objectId, item name and a pointer to the user who saved the item as a favourite.
And with this information I am trying to write a cloud code script in javascript. That will match the an item(s) to the item(s) that a user has favourited and send them a push notification saying where and what the item is and the location of the item. I have some code that will do that but this code will send a different notification for each item which could get annoying for the user here is that code.
Parse.Cloud.define("push", function(request, response) {
var TestItem = Parse.Object.extend("TestItem");
var query = new Parse.Query(TestItem);
query.limit(1000);
query.equalTo('school', 'Union College (NY)');
query.find({
success: function(resultsItem) {
//console.log("Successfully retrieved " + resultsItem.length + " :1111.");
for (var i = 0; i < resultsItem.length; i++) {
var object = resultsItem[i];
var item = object.get('item');
var school = object.get('school');
var meal = object.get('meal');
var meal = meal.toLowerCase();
var diningLocation = object.get('schoolMenu');
//var itemArray = [];
var UserFavourite = Parse.Object.extend("UserFavourite");
var queryFavourite = new Parse.Query(UserFavourite);
queryFavourite.limit(1000);
queryFavourite.equalTo("item", item)
queryFavourite.equalTo("school", school)
queryFavourite.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var objectFav = results[i];
var user = objectFav.get('user');
var userID = user.id;
var realItem = objectFav.get('item');
console.log(objectFav.get('user'));
console.log(objectFav.get('item'));
var UserClass = Parse.Object.extend("User");
var queryUser = new Parse.Query(UserClass);
queryUser.get(userID, {
success: function(userResult) {
console.log(userResult.get('school'));
console.log('install:' + userResult.get('installation').id);
var userInstallationId = userResult.get('installation').id;
var queryInstallation = new Parse.Query(Parse.Installation);
queryInstallation.equalTo('objectId', userInstallationId);
queryInstallation.find({
success: function(results) {
console.log('number' + results.length);
Parse.Push.send({
// deviceType: [ "ios" ],
where: queryInstallation,
data: {
alert: realItem + " is being served at " + diningLocation + " for " + meal
}
},
{
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
},
error: function(error) {
console.log('error');
}
});
},
error: function(error) {
console.log('error');
}
});
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
});
As you can see it is quite long and not very nice looking, I tried to save items to an array so to avoid sending two or more notifications but couldn't get that to work.
So I started writing another script that uses promises which looks much nicer but haven't gotten it all the way right now, it can match the items to users that have an item favourited and put the objectId's of those users in an array. Here is that code.
Parse.Cloud.define("test", function(request, response) {
var UserFavourite = Parse.Object.extend("UserFavourite");
var queryFavourite = new Parse.Query(UserFavourite);
var userArray = [];
var TestItem = Parse.Object.extend("TestItem");
var query = new Parse.Query(TestItem);
query.limit(1000);
query.equalTo('school', 'Union College (NY)');
query.find().then(function(results) {
return results;
}).then(function(results) {
var promises = [];
for (var i = 0; i < results.length; i++) {
var object = results[i];
var item = object.get('item');
var school = object.get('school');
var meal = object.get('meal');
var UserFavourite = Parse.Object.extend("UserFavourite");
var queryUser = new Parse.Query(UserFavourite);
queryUser.equalTo("item", item);
queryUser.equalTo("school", school);
var prom = queryUser.find().then(function(users) {
for (var i = 0; i < users.length; i++) {
var user = users[i];
var userID = user.get('user').id;
if (userArray.indexOf(userID) === -1) {
userArray.push(userID);
}
}
return userArray;
});
promises.push(prom);
}
return Parse.Promise.when.apply(Parse.Promise, promises);
}).then(function(results) {
console.log(userArray);
});
});
But now with this code I don't know where to go, I think using promises and such is the right way to go but I am now confused as once I have all the users that have an item favourited what to do, I then need to get there items that are favourited and are available in the TestItem class, this is where I am struggling.
Here is a pic of my UserFavourite class it has a pointer to the user who favorited the item as you can see, and also a user has more than one favorite.
Thanks a bunch for the help in advance.
Here is your code, and I changed a couple things.
Parse.Cloud.define("getAllFavoriteItems", function (request, response) {
var TestItems = Parse.Object.extend("TestItems");
var UserFavorites = Parse.Object.extend("UserFavorites");
var testItemsQuery = new Parse.Query(TestItems);
var userFavoritesQuery = new Parse.Query(UserFavorites);
testItemsQuery.equalTo('school', 'Union College (NY)');
userFavoritesQuery.include('testItems'); //This makes sure to pull all of the favorite item data instead of just the pointer object
userFavoritesQuery.matchesQuery('testItem', testItemsQuery); //This will run this second query against the TestItems
userFavoritesQuery.limit(1000); //limit results to 1000
userFavoritesQuery.ascending('userId'); //group the user id's together in your array
userFavoritesQuery.find({
success:function(results) {
var pushNotificationMessage = "";
var userId = "";
for (var i=0; i <results.length; i++) {
if (results[i].get('userId') != userId) {
if (results[i].get('userId') != "") {
//TODO send push notification
}
userId = results[i].get('userId');
pushNotificationMessage = ""; //start a new push notification
}
pushNotificationMessage += results[i].get('item').get('name') + ": " + results[i].get('item').get('location') + "\n";
//SOMEWHERE BEFORE HERE I NEED THE INSTALLATION ID OF THE USER
//TO SEND THE PUSH TO THAT USER
Parse.Push.send({
// deviceType: [ "ios" ],
where: queryInstallation,
data: {
alert: pushNotificationMessage
}
},
{
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
}
response.success(true);
},
error:function(error) {
response.error();
}
})
});
Some code that might create push per user, rough outline though
if (i > 0) {
if (results[i].get('user') === results[i-1].get('user')) {
userItems.push(results[i]);
}
else {
userItems.length = 0;
}
}
else {
userItems.push(results[i]);
}
Not sure let me know if you understand what I'm trying to do...
So it a user has two items favourited I want it to group that into one, phrase that says what and where both items are being served
And here is code to send push
Parse.Push.send({
// deviceType: [ "ios" ],
where: queryInstallation,
data: {
alert: pushNotificationMessage
}
},
{
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
It can also be done with then/ promises,
I agree with #Maxwell that your UserFavorite should have links to both User and TestItem. This makes it possible to make your cloud-function as simple as:
Parse.Cloud.define("getAllFavoriteItems", function(request, response) {
var TestItem = Parse.Object.extend("TestItem");
var UserFavorites = Parse.Object.extend("UserFavorites");
var testItemsQuery = new Parse.Query(TestItem);
var userFavoritesQuery = new Parse.Query(UserFavorites);
testItemsQuery.equalTo('school', request.params.school);
userFavoritesQuery.include('testItem');
userFavoritesQuery.include('user');
userFavoritesQuery.matchesQuery('testItem', testItemsQuery); //This will run this second query against the TestItems
userFavoritesQuery.find().then(function(results) {
var alerts = {};
for(var i =0 ; i<results.length; i++ ){
var user = results[i].get('user');
var testItem = results[i].get('testItem');
if(user && testItem){
var instId = user.get('installationId');
if(!alerts[instId]) {
alerts[instId] = [];
}
var m = results[i].get('item') + " is being served at {{diningLocation}} for " + testItem.get('meal');
alerts[instId].push(m);
}
}
response.success(alerts);
}, function(error) {
response.error();
});
});
This is working code that you can also find in my github repo.
You can also see the working demo here
The idea is the same as in Maxwell's answer: to have link in UserFavorites class to both User (where installationId is located) and TestItem entities. I've just made it working by including user and testItems properties in query, so when the result is returned filtered by school name I already have a list of installationIds.
Here is my schema:
User
TestItem
UserFavorites
Update:
In this code I added push notifications:
Parse.Cloud.define("getAllFavoriteItems", function(request, response) {
var TestItem = Parse.Object.extend("TestItem");
var UserFavorites = Parse.Object.extend("UserFavorites");
var testItemsQuery = new Parse.Query(TestItem);
var userFavoritesQuery = new Parse.Query(UserFavorites);
testItemsQuery.equalTo('school', request.params.school);
function SendPush(installationId, msg) {
var query = new Parse.Query(Parse.Installation);
query.equalTo('objectId', installationId);
Parse.Push.send({
where: query,
data: {alert: msg}
});
}
userFavoritesQuery.include('testItem');
userFavoritesQuery.include('user');
userFavoritesQuery.matchesQuery('testItem', testItemsQuery); //This will run this second query against the TestItems
userFavoritesQuery.find().then(function(results) {
var groupedAlerts = {};
// manually iterating though results to get alert strings ang group by user in groupedAlerts[installationId]
for(var i =0 ; i<results.length; i++ ){
var user = results[i].get('user');
var testItem = results[i].get('testItem');
if(user && testItem){
var instId = user.get('installationId');
if(!groupedAlerts[instId]) {
groupedAlerts[instId] = [];
}
var m = results[i].get('item') + " is being served at {{dining Location}} for " + testItem.get('meal');
groupedAlerts[instId].push(m);
}
}
// reformat to array and send push notifications
var alerts = [];
for(var key in groupedAlerts) {
alerts.push({
installationId: key,
alerts: groupedAlerts[key],
});
// Send push notifications
SendPush(key, groupedAlerts[key].join());
}
response.success(alerts);
}, function(error) {
response.error();
});
});
I've also updated test data in live demo (just press Get Alerts) or feel free to play around with test data hot it changes cloud code response. gitnub repo is also up to up to date.
This is based on what I understand as the problem you're trying to solve. If it's not addressing the right issue, let me know and I'll see what I can do.
Looking first at your database model, we can simplify this a bit by modifying the UserFavorites table. Starting with the initial two classes, you have a table of items and a table of users. Since a user can favorite many items and an item can be favorited by many users, we have a many-to-many relationship that exists. When this happens, we need to make a third class that points to each of the other two classes. This is where the UserFavorites table comes into play. In Parse terms, the UserFavorites table needs to have two pointers in it: one for the user and one for the item.
Once the UserFavorite table exists with it's two pointers, we can do a few things fairly easily. In your case, we have a few searching criteria:
each item must be at a given school
you want to limit your responses to the first 1000
To accomplish this you can combine two queries into one by calling matchesQuery.
Parse.Cloud.define("getAllFavoriteItems", function (request, response) {
var TestItems = Parse.Object.extend("TestItems");
var UserFavorites = Parse.Object.extend("UserFavorites");
var testItemsQuery = new Parse.Query(TestItems);
var userQuery = new Parse.Query(Parse.User);
var userFavoritesQuery = new Parse.Query(UserFavorites);
testItemsQuery.equalTo('school', 'Union College (NY)');
userQuery.include('Installation');
userFavoritesQuery.include('testItems'); //This makes sure to pull all of the favorite item data instead of just the pointer object
userFavoritesQuery.include('User'); //This makes sure to pull all of the favorite item data instead of just the pointer object
userFavoritesQuery.matchesQuery('testItem', testItemsQuery); //This will run this second query against the TestItems
userFavoritesQuery.matchesQuery('user', userQuery); //This will run the third query against Users, bringing the installation data along with it
userFavoritesQuery.limit(1000); //limit results to 1000
userFavoritesQuery.ascending('userId'); //group the user id's together in your array
userFavoritesQuery.find({
success:function(results) {
...
},
error:function(error) {
response.error();
}
})
})
Once we get that far, then compiling the push message for each user should be a matter of straight-forward string parsing logic. For example, in the success function, one way we can extract the data we is this:
success:function(results) {
var pushNotificationMessage = "";
var userId = "";
for (var i=0; i <results.length; i++) {
if (results[i].get('userId') != userId) {
if (results[i].get('userId') != "") {
//TODO send push notification
}
userId = results[i].get('userId');
pushNotificationMessage = ""; //start a new push notification
}
pushNotificationMessage += results[i].get('item').get('name') + ": " + results[i].get('item').get('location') + "\n";
}
response.success(true);
}
I haven't tested these examples to see if they'll work, but I hope this gives you an idea of how to simplify your queries into something a little more manageable.

Categories