Using objectid in JavaScript - javascript

I have a JavaScript table getting parse data need to use the objectid of each row for a later date need to store them in variable or something like that
Can any help me.
Cheers
UPDATE 1
Here is some code to help
var firstTeamResults = Parse.Object.extend(strUser);
var query = new Parse.Query(firstTeamResults);
query.startsWith("NameGame", ask4);
query.descending("updateAt");
query.find(
{
success: function(results)
{
for (var i = 0; i < results.length; i++)
{
var object = results[i];
(function($) {
$("#first-team-results-table").append("<tr><td>"
+ object.get("NameGame")
+ "</td><td>"
+ object.get("item")
+ "</td><td>"
+ "<input id='video' type='submit' value='Video'/>"
+ "</td><td>"
+ object.get("des")
+ "</td><td>"
+ object.get("group")
+ "</td><td>"
+ "<input id='more' type='submit' value='More'/>"
+ "</td></tr>");
})(jQuery);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
})
});

I think I understand what you're trying to ask. After you query the objects and get them, you can just call the .id method on each object to get the objectId.
See the example below.
var YourClass = Parse.Object.extend("YourClassName");
var query = new Parse.Query(YourClass);
//An unconstrained Query to get all objects in the table
query.find({
success: function(results) {
for(var i=0; i <results.length; i++){
var objectId = results[i].id //This returns you the objectId of each row
//You can do what you want with objectId now.
}
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
The Parse Docs show that you can retrieve the three special properties of every object by using the methods below.
var objectId = yourObject.id;
var updatedAt = yourObject.updatedAt;
var createdAt = yourObject.createdAt;

Related

How to access HTML input element on javascript

I'm trying to retrieve the customers name by alert based on the account number that's entered into the textbox by i'm having trouble referencing the textbox (>>txtFree<<). I just not sure what i must replace it with if anyone could help please.
HTML
Account Number: <input type="text" id="txtFreeBank" name="txtFreeBank" />
JS
function checkBankAc() {
var txtFree = parseFloat(document.getElementById('txtFreeBank').value);
var bankdetails = Parse.Object.extend("BankDetails");
var query = new Parse.Query(bankdetails);
query.equalTo("AccountNum", >>txtFree<<);
query.find({
success: function (results) {
alert("Successfully retrieved " + results.length + " scores.");
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('CustomerName'));
}
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
You will be able to access the data entered switching your >>txtFree<< for the following:
document.getElementById('txtFreeBank').value

How to fetch or convert Parse query into array (JavaScript SDK)

I have a column in my Parse database populated with numbers and I'm trying to add them all together to get a total.
I know how to do the adding together if the data returned is a single array, but I can only figure out how to return the numbers as individual objects. This is my code which does that:
var query = new Parse.Query(Services);
query.exists("costMonthly");
query.find({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
console.log(object.get('costMonthly'));
}
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
How would I go about fetching what I want as an array or at least converting what I have into one?
It looks like you are trying to sum the costMonthly field. You can use reduce to do this easily:
var query = new Parse.Query(Services);
query.exists("costMonthly");
query.find({
success: function (results) {
var sum = results.reduce(function(prev, cur) {
return prev + cur.get('costMonthly');
}, 0);
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
If your goal is an array of the costMonthly values, this will work:
var monthlyCosts = results.map(function(item) {
return item.get('costMonthly');
});
Read more about reduce here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
You can create a temporary array , and push results though through iteration , not the best solution , but is very useful if you want to manipulate results later :
var costMonthlyArray=[];
var query = new Parse.Query(Services);
query.exists("costMonthly");
query.find({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
var cost=object.get('costMonthly');
costMonthlyArray.push(cost);
console.log(cost);
}
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});

Javascript error with sort

i have this code as shown below,
i got this from a developer who went afk because he has family troubles
basically this code below should grab the json results and form them into a table after sorting the price and then placing it in the table.
heres the code
//first define a function
var sortTable = function () {
$("#tableid tbody tr").detach().sort(function (a, b) {
//substring was added to omit currency sign, you can remove it if data-price attribute does not contain it.
return parseFloat($(a).data('price').substring(1)) - parseFloat($(b).data('price').substring(1));
})
.appendTo('#tableid tbody');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'api link here',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
//and here is the 2nd js file
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: '2nd api',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
Accessing the DOM, to get data that needs to be sorted, is a bad practice IMO. Even worse when you had the results in raw JSON form in the first place (in the success callback of the ajax call). Your success function should do something like this
success: function (json) {
//first sort the results - or better store these results somewhere
//and use that as a data store that is responsible for what is rendered in the DOM
json.results.sort(function(a,b) {
//using substring and parseFloat just like it was done in sortTable
//assuming price field has prices as strings with currency symbol in the first place
return parseFloat(a.substring(1)) - parseFloat(b.substring(1))
});
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
}

Parse query working, but results showing as undefined or not found

The below code successfully runs a query and returns the results. However when being displayed on the page, the label for
item.username and item.imageURL
are returning as undefined or in the images case "not found).
I believe I may have to change the code which is displaying this on the page, because a recent query change is now returning multiple possibilities for username:
Before it just returned fromUser for this, now the query also can potentially return toUser. However the resulsts on the page should only show one or the other, not both.
Just stuck on what I need to adjust below to allow this?
var currentUser = Parse.User.current();
var FriendRequest = Parse.Object.extend("FriendRequest");
var queryOne = new Parse.Query(FriendRequest);
queryOne.include('fromUser');
queryOne.include("myBadge");
queryOne.equalTo("fromUser", currentUser);
var queryTwo = new Parse.Query(FriendRequest);
queryTwo.include('toUser');
queryTwo.include("myBadge");
queryTwo.equalTo("toUser", currentUser);
var mainQuery = Parse.Query.or(queryOne, queryTwo);
mainQuery.equalTo("status", "Connected");
mainQuery.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('fromUser').get('pic'),
username: results[i].get('fromUser').get('username'),
userId: results[i].get('fromUser').id,
status: results[i].get('status'),
// Saves the object so that it can be used below to change the status//
fetchedObject: results[i]
});
}
var select = document.getElementById("FriendsConnected");
$.each(friends, function(i, v) {
var opt = v.username;
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
})
$('#containerFriends').empty();
$('#containerFriendsConnected').empty();
_.each(friends, function(item) {
var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
wrapper.append('<img class="responsive-image friendImgOutline" src="' + item.imageURL + '" />'+ '<br>');
wrapper.append('<div class="tag">' + item.username + '</div>');
wrapper.append('<div type="button" class="btn btn-danger mrs decline">' + 'Unfriend' + '</div>');
$('#containerFriends').append(wrapper);
//The following lets the user accept or decline a friend request by changing the status the status from Pending to Declined/////
$(document).on('click', function() {
$(".decline").click(function() {
item.fetchedObject.set("status", "Rejected");
item.fetchedObject.save(null, {
success: function(results) {
console.log("REJECTED");
},
error: function(contact, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
alert("Error: " + error.code + " " + error.message);
}
});
});
});
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
The mainQuery needs to include the keys as well.
var mainQuery = Parse.Query.or(queryOne, queryTwo);
mainQuery.include("toUser"); //Add this line
mainQuery.include("fromUser"); //Add this line
mainQuery.equalTo("status", "Connected");

Changing the objectId thats returned in a query to that of the actual user

Using parse.com and JavaScript SDK.
This is what I'm attempting to achieve.
A list of users (friends) is returned on the page to the user, They can then click on one of these users and the page is updated to list all of that users items (which are basically images).
This query works correctly and returns a list of users.
var currentUser = Parse.User.current();
var FriendRequest = Parse.Object.extend("FriendRequest");
var query = new Parse.Query(FriendRequest);
query.include('toUser');
query.include('SentTo');
query.include("myBadge");
query.equalTo("fromUser", currentUser);
query.equalTo("status", "Request sent");
query.find({
success: function (results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('toUser').get('pic'),
friendRequestId: results[i].id,
username: results[i].get('toUser').get('username')
});
}
// TW: replaced dynamic HTML generation with wrapper DIV that contains IMG and name DIV
_.each(friends, function (item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div class="wrapper" data-friend-request-id="' + item.friendRequestId + '"></div>');
wrapper.append('<img class="images" src="' + item.imageURL + '" />');
wrapper.append('<div>' + item.username + '</div>');
$('#container').append(wrapper);
});
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
****This below query should contain the user who has selected above and stored in window.selectedFriendRequestId (which is saved in the variable friendRequest ****
This query looks at the myBadges class and the user reference "SentTo" the ref used is for example a3aePaphBF which is the actual _User objectID.
function FriendProfile() {
var friendRequest = "window.selectedFriendRequestId";
console.log(window.selectedFriendRequestId);
var myBadges = Parse.Object.extend("myBadges");
var query = new Parse.Query(myBadges);
query.equalTo("SentTo", friendRequest);
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('BadgeName'));
}
// If the imageURLs array has items in it, set the src of an IMG element to the first URL in the array
for (var j = 0; j < imageURLs.length; j++) {
$('#imgs').append("<img src='" + imageURLs[j] + "'/>");
}
},
error: function (error) {
// If the query is unsuccessful, report any errors
alert("Error: " + error.code + " " + error.message);
}
});
}
The issue is that the first query is not returning an objectId that I can use in the second query as a reference. For example a3aePaphBF is not returned but cr3LG70vrF is.
How to I return the actual _User objectid in the first query so I can make these match?
To get the ID of a user:
results[i].get('toUser').id
So if you update your section of code that is doing friends.push(...):
friends.push({
imageURL: results[i].get('toUser').get('pic'),
friendRequestId: results[i].id,
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').id
});
Then in your bit where you create the wrapper:
_.each(friends, function (item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div class="wrapper"'
+ ' data-friend-request-id="' + item.friendRequestId + '"'
+ ' data-to-user-id="' + item.userId + '"></div>');
wrapper.append('<img class="images" src="' + item.imageURL + '" />');
wrapper.append('<div>' + item.username + '</div>');
$('#container').append(wrapper);
});
Notice that I've added another data-property to hold the ID of the toUser.
Now if you followed the tips from your other question, you can tweak the code that attaches the on-click handler to pass toUserId also:
$('#container').on('click', '.wrapper', function () {
var wrapper = $(this);
var friendRequestId = wrapper.data('friendRequestId');
var toUserId = wrapper.data('toUserId');
FriendProfile(friendRequestId, toUserId);
// other code ...
});
Lastly your FriendProfile() function can now use either of those parameters as needed:
function FriendProfile(friendRequestId, toUserId) {
var toUser = new Parse.User();
toUser.id = toUserId;
var myBadges = Parse.Object.extend("myBadges");
var query = new Parse.Query(myBadges);
query.equalTo("SentTo", toUser);
// ... etc ...
}
NOTE: The User class should be locked down for privacy reasons, you shouldn't be able to read any properties of other users except in Cloud Code when you have the following line in your Cloud Function:
Parse.Cloud.useMasterKey();

Categories

Resources