Alternative to using JS .load? - javascript

Is there an alternative to using .load to refresh the contents of a Div? Bascially I'm using .load below to reload the div after an object has been removed. But at the moment this is'nt working correctly.
.load is returning a div without results, even though there should be objects within it. When I refresh the page manually the correct results show.
Therefore, Could I just remove the object from view the user has clicked on instead?
/////////////////////SECTION 1 - This code block returns the current users friends to the page. THIS IS NOT USED IN THE FILTER//////
$('#containerFriends').empty();
$('#friendsProfile').hide();
$('#container').empty();
$('#containerFriendsConnected').empty();
var currentUser = Parse.User.current();
var FriendRequest = Parse.Object.extend("FriendRequest");
var queryOne = new Parse.Query(FriendRequest);
queryOne.equalTo("toUser", currentUser);
var queryTwo = new Parse.Query(FriendRequest);
queryTwo.equalTo("fromUser", currentUser);
var mainQuery = Parse.Query.or(queryOne, queryTwo);
mainQuery.include('toUser');
mainQuery.include('fromUser');
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('toUser').get('pic'),
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').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/////
wrapper.children('.decline').click(function() {
$(".decline").click(function() {
item.fetchedObject.set("status", "Rejected");
$( "#containerFriends" ).load("friends.html #containerFriends" );
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);
}
});

Related

Trying to get the JavaScript variable scope correct in this trello.get code

I have been struggling to set the variable 'listName' scope correct in this code ...
var loadedAtriskopps = function(opps) {
var listName = 'empty';
$.each(opps.cards, function(index, opp) {
Trello.get(
'/cards/' + opp.id + '/list?fields=name', {fields: "id, name"}, function(list, err) {
var listName = list.name;
console.log(listName); //this returns the correct value
});
console.log(listName); //this returns 'empty'
var opp = $("<div class='row'><div class='col-xs-6'><p class='output'>" + opp.name + "</b><br>On List: " + listName + " </p></div> </div>");
$('#opps').append(opp)
});
};
Inside the Trello.get function it returns correctly, but not outside of it. After hours of research, still cannot get it right.
UPDATE:
Per the recommendation, tried this code:
var loadedAtriskopps = function(opps) {
var listName = 'empty';
$.each(opps.cards, function(index, opp) {
console.log(opp.name); // returns correct value
Trello.get('/cards/' + opp.id + '/list?fields=name', {fields: "id, name"})
.success(function(list) {
listName = list.name;
console.log(listName); // // returns correct value
// next line errors "Uncaught TypeError: Cannot read property 'name' of undefined" but listName is correct
var opp = $("<div class='row'><div class='col-xs-6'><p class='output'>" + opp.name + "</b><br>On List: " + listName + " </p></div> </div>");
$('#opps').append(opp);
})
.error(function(err) {
console.log("An error: " + err);
});
});
};
Seems I have lost definition for the opp object with in the success callback.
SOLUTION:
var loadedAtriskopps = function(opps) {
var listName = 'empty';
$.each(opps.cards, function(index, opp) {
Trello.get('/cards/' + opp.id + '/list?fields=name', {fields: "id, name"})
.success(function(list) {
listName = list.name;
var card = $("<div class='row'><div class='col-xs-6'><p class='output'>" + opp.name + "</b><br>On List: " + listName + " </p></div> </div>");
$('#opps').append(card);
})
.error(function(err) {
console.log("An error: " + err);
});
});
};
Thank you Darren and Andy!
I believe you need to move your post-ajax operations into a success callback. This should ensure you have the actual value after the ajax has the value of listName.
var loadedAtriskopps = function(opps) {
var listName = 'empty';
$.each(opps.cards, function(index, opp) {
Trello.get('/cards/' + opp.id + '/list?fields=name', {fields: "id, name"})
.success(function(list) {
listName = list.name;
console.log(listName); // should return correct value
var _opp = $("<div class='row'><div class='col-xs-6'><p class='output'>" + opp.name + "</b><br>On List: " + listName + " </p></div> </div>");
$('#opps').append(_opp);
})
.error(function(err) {
console.log("An error: " + err);
});
});
};

Comparing to a user object in ParseQuery and facing error 102

I am trying to find out all the records that matches a user from a Parse class (namely, UserBeaconTracking). I am able to get correct user object and beacon object to begin with. However, when I use the statement
userBeaconTrackingQuery.equalTo("user", user);
Returned Error 102 with an error message "value is expected instead of map type."
What is it that I am doing wrong?
Here is the code snippet:
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo("username", username);
userQuery.find().then(function(currentUser) { // get the user who sent the request
user = currentUser;
console.log("User" + JSON.stringify(user) + "Beacon Name :: " + JSON.stringify(visitedBeaconName));
}).then(function () { // get the beacons with which user communicated
var beaconRelation = Parse.Object.extend("Beacon");
var beaconQuery = new Parse.Query(beaconRelation);
beaconQuery.equalTo("name", visitedBeaconName);
return beaconQuery.find();
}).then(function (beacons) { // get user beacon transaction details
console.log("number of beacons " + beacons.length + " " + beacons[0]);
visitedBeacon = beacons[0];
console.log("beacon :: " + visitedBeacon);
var userBeaconTracking = Parse.Object.extend("UserBeaconTracking");
var userBeaconTrackingQuery = new Parse.Query(userBeaconTracking);
userBeaconTrackingQuery.equalTo("user", user);
userBeaconTrackingQuery.equalTo("beacon", visitedBeacon);
userBeaconTrackingQuery.find({
success : function (results) {
visitCounter = results[0].get("count");
console.log ("Visit Counter :: " + visitCounter);
// get the list of stores associated with the beacon
var beaconTable = Parse.Object.extend("Beacon");
var brandsAssociatedWithBeacon = new Parse.Query(beaconTable);
brandsAssociatedWithBeacon.get(visitedBeacon.id).then(function(beacon) {
typeOfBeacon = beacon.get("type");
console.log("Beacon Type ::" + typeOfBeacon);
var beaconBrandRelation = beacon.relation("brand");
var query = beaconBrandRelation.query();
//return query.find();
});
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
});

Parse.com, Javascript, Tables

I have a javascript table that is displaying data that is store in a parse.com server, i also have a iOS App that is also getting the same data from the same place on the iOS App it is every for row that has been selected in the table to store the object id in an NSString to be used in other like adding it a favourite column etc however on the javascript side i have not been very successful at this can one help?
iOS
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{[tableView deselectRowAtIndexPath:indexPath animated:YES];
PFObject *tempObject = [HomeArray objectAtIndex:indexPath.row];
NSLog(#"%#", tempObject.objectId);
_NameOfGame.text = [tempObject objectForKey:#"NameGame"];
_Items.text = [tempObject objectForKey:#"item"];
_Des.text = [tempObject objectForKey:#"des"];
userFirstname = [tempObject objectForKey:#"FirstName"];
group = [tempObject objectForKey:#"group"];
device = [tempObject objectForKey:#"Device"];
together = [NSString stringWithFormat:#"Uploaded by %# from %# on a %#", userFirstname, group, device];
PFFile *video = [tempObject objectForKey:#"Video"];
_videoUrl = video.url;
NSLog(#"got a video %#", _videoUrl);
_deleteObjectID = [HomeArray objectAtIndex:indexPath.row];
NSLog(#"%#", _deleteObjectID);
[self animateDetailView];}
Javascript
var GameScore = Parse.Object.extend("games");
var query = new Parse.Query(GameScore);
query.equalTo("group", strUser)
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>"
+"<input type='checkbox' data-id='" + object.id + "'/>" $(checkBox).appendTo("#modifiersDiv")
+ "</td><td>"
+ object.get("NameGame")
+ "</td><td>"
+ object.get("item")
+ "</td><td>"
+ object.get("des")
+ "</td></tr>");
})(jQuery);
}
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
})
});
I have try with checkboxes in javascript but no luck
In which way aren't you successful? What doesn't work?
Do you get the correct result at all? If not change this line
query.equalTo("group", strUser) && query.equalTo("month", res);
to
query.equalTo("group", strUser);
query.equalTo("month", res);
------------------------------------ EDIT -------------------------
I would rewrite it like this:
var GameScore = Parse.Object.extend("games"),
query = new Parse.Query(GameScore),
$table = $("#first-team-results-table"),
tableString;
appendToTable = function (object) {
tableString = "<tr><td><input type='checkbox' data-id='"+object.id+"'</td><td>"+object.get("NameGame")+"</td><td>"+object.get("item")+"</td><td>"+object.get("des")+"</td></tr>";
$table.append(tableString);
$(checkBox).appendTo("#modifiersDiv"); // I don't know what the checkbox-variable represents... anyway use this line to do something with it ;)
};
query.equalTo("group", strUser)
query.find({
success: function(results){
var object;
for (var i = results.length - 1; i >= 0; i--) {
object = results[i];
appendToTable(object);
};
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
I'm not sure what you are doing here
$(checkBox).appendTo("#modifiersDiv")
but I hope it gets you in the right direction...
------------------------------------ EDIT -------------------------
okay retry, still not sure if I get what you're trying to do. The following will first display the table after fetching stuff from Parse.com and putting it to the #objectBox-div when clicking the 'more'-button
HTML
<div id="buttonShow"> <input type="submit" id="uploadPaid" value="More"/><input type="text" id="gotObject" class="textFields"/> </div>
<table id="first-team-results-table"></table>
<div id="objectBox"></div>
JS
(function() {
var GameScore = Parse.Object.extend("games"),
query = new Parse.Query(GameScore),
$table = $("#first-team-results-table"),
$objectBox = $('#objectBox'),
tableString,
divString,
ParseGames;
appendToTable = function (object) {
tableString = "<tr><td><input class='check' type='checkbox' data-id='"+object.id+"'</td><td>"+object.get('NameGame')+"</td><td>"+object.get('item')+"</td><td>"+object.get('des')+"</td></tr>";
$table.prepend(tableString);
};
appendToDiv = function (object) {
divString = "<p><span>"+object.get('NameGame')+"</span> <span>"+object.get('item')+"</span> <span>"+object.get('des')+"</span></p>";
$objectBox.append(divString);
};
query.equalTo("group", strUser)
query.find({
success: function(results){
ParseGames = results;
for (var i = results.length - 1; i >= 0; i--) {
appendToTable(results[i]);
};
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
$("#uploadPaid").on('click', function (e) {
e.preventDefault();
$objectBox.html('');
$('.check').each(function(index) {
console.log($(this).is(':checked'));
if ($(this).is(':checked')) {
appendToDiv(ParseGames[index]);
};
});
});
})();
good luck ;)
After a couple of days look through website and trying lots of code i have finally got an answer to my question.
<table id="first-team-results-table" class="table1" border="1xp" style="width:100%">
<col width="80">
<col width="80">
<col width="5">
<col width="300">
<col width="100">
<tbody>
<tr>
<th>Name Of Game</th>
<th>Item</th>
<th>Video</th>
<th>Description</th>
<th>Group</th>
</tr>
</tbody>
</table>
<script type="text/javascript">
Parse.initialize("API1", "API2" );
var firstTeamResults = Parse.Object.extend("ukgames");
var query = new Parse.Query(firstTeamResults);
//query.equalTo("favs", id);
//"group" , group
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>"
+ "<input type='checkbox' class='chkNumber' value='"+object.id+"'/>"
+ "</td><td>"
+ object.get("NameGame")
+ "</td><td>"
+ object.get("item")
+ "</td><td>"
+ object.get("des")
+ "</td><td>"
+ object.get("group")
+"</td></tr>");
})(jQuery);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
<div id="buttonShow">
<input type="button" class="btnGetAll" value="More"/>
<input type="text" id="gotObject" class="textFields"/>
</div>
<script type="text/javascript">
$(function () {
$('.btnGetAll').click(function () {
if ($('.chkNumber:checked').length) {
var chkId = '';
$('.chkNumber:checked').each(function () {
chkId += $(this).val() + ",";
});
chkId = chkId.slice(0, -1);
alert(chkId);
}
else {
alert('Nothing Selected');
}
});
$('.chkSelectAll').click(function () {
$('.chkNumber').prop('checked', $(this).is(':checked'));
});
$('.chkNumber').click(function () {
if ($('.chkNumber:checked').length == $('.chkNumber').length) {
$('.chkSelectAll').prop('checked', true);
}
else {
$('.chkSelectAll').prop('checked', false);
}
});
});
</script>

Can I use .click to target only one result in a query that returns multiple results?

This code block returns multiple results, which are then shown to the user on the page. At the moment when the user clicks on any of the button here
wrapper.append('<div type="button" class="btn btn-danger mrs decline">' + 'Unfriend' + '</div>');
Instead of just declining one object, all objects are declined. Which is not what I want.
To make this function correctly, would it be correct to be looking to something like the following instead?
$('.decline).css('cursor', 'pointer');
--
mainQuery.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('toUser').get('pic'),
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').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() {
//Note 1////
$(".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);
}
});
});
You need to bind the handler just to the specific element, not all .decline elements. Remove the $(document).on('click', ...) handler, and change it to:
wrapper.children('.decline').click(function() {
...
});
There is an error in your code here $('.decline).css('cursor', 'pointer'); you should add an ' after the name of the class so it should look like this $('.decline').css('cursor', 'pointer');

After function is run, how to stop duplication of displayed results on the page?

Via a drop down box, the below function runs. It will place images of friends the user is connected to onto the page, via #containerFriendsConnected . But if the user selects "Connected Friends" multiple time from the drop down box, the user images are replicated.
Say the user has 2 friends, if you click the drop down box option 3 seperate times,the page will repeat the 2 friends and show them 3 times each on the page (6 images in total).
I presume I need to add some simple if statement that stops this? Something like
For (var i = 0; i < results.length; i++) {
});
This is where I'm stuck.
FUNCTION THAT REPEATS IMAGES
function FriendsConnected() {
$('#containerFriendsRejected').empty();
$('#containerFriendsPending').empty();
$('#containerFriendsRequestSent').empty();
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", "Connected");
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'),
userId: results[i].get('toUser').id
});
}
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);
})
_.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>');
$('#containerFriendsConnected').append(wrapper);
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
I solved this by using .empty();
At the following point
$('#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>');
$('#containerFriendsConnected').append(wrapper);
});

Categories