Saving data to parse using javaScript SDK - javascript

Using parse.com and JavaScript SDK.
- Section one shows a list of objects
- Section two lets the user select one of those objects and add to a modal box
- Section three saves the data to parse
What I'm unable to work out is how I can save the section 1 item.badgename and item.category to parse.
I've tried adding myBadge.set("category", badgename.toString()); to section 3, but I get a undefined error. i'm not sure how to define this before trying to save.
Really need some help and an example to follow.
3 -Saves the badge details to parse
var MyBadge = Parse.Object.extend("myBadges");
var FriendRequest = Parse.Object.extend("FriendRequest");
var friendRequest = new FriendRequest();
friendRequest.id = window.selectedFriendRequestId;
var badgeselected = $('#badgeselect .go').attr("src");
$(document).ready(function() {
$("#send").click(function() {
var myBadge = new MyBadge();
var badgeselected = $('#badgeselect img').attr("src");
var BadgeSentTo = $('#selectFriend').val();
var categorySelected = $('#category').val();
var uploadercomment = $('#UploaderComment').val();
myBadge.set("BadgeName", badgeselected); //got this working using .set
myBadge.set("Comment", uploadercomment); //got this working using .set
myBadge.set("category", categorySelected);
myBadge.set("SentTo", new Parse.User({
id: BadgeSentTo
}));
myBadge.set("uploadedBy", Parse.User.current());
myBadge.save(null, {
success: function(results) {
console.log("Done");
//location.reload();
},
error: function(contact, error) {
// The save failed.
alert("Error: " + error.code + " " + error.message);
}
});
return false;
});
});
** 1- Returns results to the page for user to select**
var GlobalBadges = Parse.Object.extend("Global_Badges");
var query = new Parse.Query(GlobalBadges);
query.exists("Global_Badges_img");
query.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('Global_Badges_img'),
//friendRequestId: results[i].id,
badgename: results[i].get('BadgeName'),
category: results[i].get('category')
});
}
// 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></div>');
wrapper.append('<img class="images BadgeImgOutline responsive-image" src="' + item.imageURL + '" />'+ '<br>');
wrapper.append('<div id="name"class="tag badgelabel" >'+ item.badgename + '</div>'+ '<br>');
wrapper.append('<div id="category" class="tag categorylabel" >'+ item.category + '</div>'+ '<br>'+ '<br>' );
$('#container').append(wrapper);
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
2 -Upon the user selecting an object from above, this adds the data to a modalbox
$(document).ready(function() {
$('.go img').css('cursor', 'pointer');
$('.go').on('click', 'img', function(e) {
$('.go img').removeClass('BadgeImgOutline');
$(this).parent().appendTo('#badgeselect');
$(this).addClass('BadgeImgOutlineSmall');
$('.go img').addClass('BadgeImgOutline');
$('#modal').reveal({
closeonbackgroundclick: true,
dismissmodalclass: 'close'
});
return false;
});
});

This was addressed by making the following changes.
- Taking the data from #badgeSelect not #category
- From section 3, the line var categorySelected = $('#category').val(); was changed to categorySelected = $('#badgeselect .categorylabel').text();
By taking the data from #badgeSelect it meant that the only data being available was that shown shown in the text box, instead of '#category'that returned all results.
The it was simply targeting the text correctly with the change to the var categorySelected

Related

Displaying images from JSON

Trying to display the cover art with the results. Something in the img src tag is causing the app not to load. If I just point the img to data.tracks[i].album.name (obviously not a real url, but enough to test if it's working) it pastes it in just fine, but the moment I change it to paste the url in place, it makes the whole app stop working.
$('#findTracks').click(function (e) {
e.preventDefault(); // override/don't submit form
$('#recommendations').empty();
var artist = $('#artist').val();
var userid = "";
var playlistid = "";
$.ajax({
url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
type: 'GET',
dataType: 'json',
success: function(data) {
if (data.tracks.length > 0) {
var tracksLength = data.tracks.length, html = '';
for (var i=0; i<tracksLength; i++) {
var href = '';
if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1) { // data.tracks[i].href
href = data.tracks[i].href;
href = 'makeReq(\''+data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+'\')';
html += '<li>' +data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+ ' <img src="' +data.tracks[i].album.images[0].url+ '" />';html += '</li>';
html += '</li>';
}
}
$('#third').css('display', 'block');
$('#recommendations').append(html);
} else {
$('#recommendations').append('<li>No matches returned.</li>');
$('#third').css('display', 'none');
}
},
error: function(err) {
alert("The Spotify API failed to return a response.");
}
});
});
This is my first time ever coding in javascript so please go easy on me! lol
EDIT:
This seems to be running well! However, many of the songs do nothing when I click on them
For example, type "Don't Stop" and only "The Black Eyed Peas - Don’t Stop The Party" works out of the first ten...anybody know why?
also, anybody known why "if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1)" is in there? If I take it out this all stops working...I am not in G.B.
If you look in the console you are getting the error
Uncaught TypeError: Cannot read property '0' of undefined
looking at the data the query returns we notice that data.tracks[i].album returns
{
"released": "2006",
"href": "spotify:album:2knAf4wg8Gff8q1bXiXCTz",
"name": "The Dutchess",
"availability": {
"territories": "MX"
}
}
there is no property images so when you call
data.tracks[i].album.images[0]
you get the undefined error, causing the script to halt execution.
I'm unfamiliar with the spootify api but taking a quick glance at the api theres the endpoint for get-album. Heres what I was able to come up with to get the album art
$.get("http://ws.spotify.com/search/1/track.json?q=Fergie",function(data){
var albumId = data.tracks[97].album.href.split(":")[2];
$.get("https://api.spotify.com/v1/albums/" + albumId,function(albumResponse){
var firstImage = albumResponse.images[0];
$('body').append($('<img/>',{
src : firstImage.url,
width : firstImage.width,
height : firstImage.height
}));
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>
You should research more into how to get the album art since I'm unsure if this is the optimal solution.
The search endpoint you mentioned is different from the one your using.
One your using
url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
One you linked to
url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
Heres your solution with the change in endpoint
$('#findTracks').click(function(e) {
e.preventDefault(); // override/don't submit form
$('#recommendations').empty();
var artist = $('#artist').val();
var userid = "";
var playlistid = "";
$.ajax({
//url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
type: 'GET',
dataType: 'json',
success: function(data) {
if (data.tracks.items.length > 0) {
data.tracks = data.tracks.items
data.artists = data.artists.items
var tracksLength = data.tracks.length,
html = '';
for (var i = 0; i < tracksLength; i++) {
var href = '';
href = data.tracks[i].href;
href = 'makeReq(\'' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + '\')';
html += '<li>' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + ' <img src="' + data.tracks[i].album.images[0].url + '" />';
html += '</li>';
html += '</li>';
}
$('#third').css('display', 'block');
$('#recommendations').append(html);
} else {
$('#recommendations').append('<li>No matches returned.</li>');
$('#third').css('display', 'none');
}
},
error: function(err) {
alert("The Spotify API failed to return a response.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Artist:
<input type="text" id="artist" />
<button id="findTracks">Find Tracks</button>
<div id="recommendations"></div>

How to update an existing object in parse following a button click? (JavaScript SDK)

Using Parse.com and JavaScript SDK.
The purpose of the below function is:
a/ Return a list of users that the current user needs to respond to a friend request.
b/ When they click cancel, the current object state changes from "Pending" to "Declined"
Part (a) works as required. Part (b) is returning the following error
Uncaught TypeError: Cannot call method 'get' of undefined
I presume this is because it cannot find "status" to change and save it from "Pending" to "Declined" ?
I've blocked out the area of code that I think is not working, but cannot get around this and need some help ;-)
//////////Returns list of Friends pending a response///////////////////
function FriendsPending() {
$('#containerFriends').empty();
$('#containerFriendsRejected').empty();
$('#containerFriendsRequestSent').empty();
$('#containerFriendsConnected').empty();
$('#userimgs').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", "Pending");
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,
status: results[i].get('status').id
});
}
var select = document.getElementById("FriendsPending");
$.each(friends, function(i, v) {
var opt = v.username;
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
})
$('#containerFriendsPending').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>');
$('#containerFriends').append(wrapper);
wrapper.append('<div type="button" class="btn btn-success mrs">' + 'Accept' + '</div>');
wrapper.append('<div type="button" class="btn btn-danger mrs decline">' + 'Decline' + '</div>');
$('#containerFriendsPending').append(wrapper);
//////Code with issues//////////////
$(document).on('click', function() {
$(".decline").click(function() {
status: results[i].get('status').id
status.set("status", "Declined");
console.log(status);
///////////////////////////
status.save(null, {
success: function(results) {
// The object was saved successfully.
location.reload();
},
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);
}
});
}
status: results[i].get('status').id
You are getting that error because you are trying to call get on results[i] which is undefined because i is undefined.
Also, the line itself is not a valid expression. If you want to assign something to a variable called "status", this is the correct syntax:
var status = ...
Further, it looks like you are treating status as an object, rather than just a field.
status: results[i].get('status')
When you want to change the status later, you need to keep a reference to the original fetched object. E.g.:
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,
status: results[i].get('status'),
fetchedObject: results[i]
});
Then later when you want to set the status on that object to declined:
item.fetchedObject.set("status", "Declined");
It is the fetchedObject you then want to save:
item.fetchedObject.save( // );

Fill a HTML table with Javascript values using Parse.com

I am looking to create a simple HTML website with the data from my iOS app displayed in tables. I use Parse.com for my mobile data, and I will be using Javascript to display it on the website.
I have developed a JSP-based website before, but this time I am using a Javascript plugin for Wordpress, so I cannot use JSP files. Therefore I will need to handle everything in HTML code.
Is there a way to get the following Parse.com query into a HTML table?
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", "Dan Stemkoski");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " scores.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('playerName'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
Create a custom page template for the page you want to show this data on. e.g. create a page called 'score-table' in Wordpress Admin and then create a page template in your theme called 'page-score-table.php'.
Include the parse library scripts in the page and jQuery if you need to (though this should be loaded by Wordpress anyway) and then use something like this.
<table id="results-table">
<tr>
<th>User Name</th>
<th>Score</th>
</tr>
</table>
...
<script>
Parse.initialize("Your", "Credentials");
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", "Dan Stemkoski");
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
(function($) {
$('#results-table').append('<tr><td>' + object.get('playerName') + '</td><td>' + object.get('score') + '</td></tr>');
})(jQuery);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
Fiddle showing it HERE, set up a dummy Parse table to show you.
Actually replace the success function with this, I believe append is quite expensive if you have a lot of rows...
...
///before query.find();
var myScores='';
...
success: function(results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
myScores+='<tr><td>' + object.get('playerName') + '</td><td>' + object.get('score') + '</td></tr>';
}
(function($) {
$('#results-table').append(myScores);
})(jQuery);
}

How to get specific entry with JS from a DB (JSON)

I'm trying to do something like a dictionary. The idea is there is a DB online. Someone can search for term and get the description from the db.
How it works:
1) whole terms from the db will be downloaded and compared with searchterm. each term has its specific ID. If the searchterm is the DB the ID will be saved.
2) The ID will be sent to the server with the DB and than it should receive the description
URL to get all Terms
http://s288617660.mialojamiento.es/api.php?rquest=terms
Url to get description
http://s288617660.mialojamiento.es/api.php?rquest=answers&param1=ID
Now this is my search function
<script>
getAllTerms();
function getAllTerms(){
var url = "http://s288617660.mialojamiento.es/api.php?rquest=terms";
$.get(url, function(data) {
localStorage.setItem("terms", JSON.stringify(data));
//alert(JSON.stringify(data));
}).done(function() { /*alert(localStorage.getItem("terms"));*/ })
.fail(function() { alert("error"); })
.always(function() { /*alert("finished");*/ });
}
function findTerm(){
var content = $("#SearchTerm").val();
//alert(content);
var id = 0;
var data = JSON.parse(localStorage.getItem("terms"));
$.each(data, function(index, term) {
//alert("My content " + content + ", term " + term.name);
if(content == term.name){
id = term.id_term;
}
});
//--------------my try to request the description
var url_answers = "http://s288617660.mialojamiento.es/api.php?rquest=answers&param1="+id;
//alert(url_answers);
var answer = "";
$.get(url_answers, function(data2) {
localStorage.setItem("answer", JSON.stringify(data2));
$.each(data2, function(index, object) {
answer = object.description+object.id_answer;
});
//-----------------end of my try
//alert(id);
var htmlStr = "";
if(parseInt(id) > 0){
//i found the term
localStorage.setItem("idterm",id);
htmlStr = "<li>" + content + "- id: " + id + answer + "</li>"
}else{
//not found
htmlStr = "<li>Term not found</li>"
}
$('#SearchList').empty();
$('#SearchList').append(htmlStr);
$('#SearchList').listview("refresh");
}
</script>
The ID request just works fine but not the description request. Why?
By the way: it's a android phonegap project

calling JQuery HTTP GET request inside javascript function

I will start off by saying I am new to Javascript and JQuery. What I want to accomplish is have a submit button on an HTML page that will call the dbQuery function in my .js file that will print the value of variables to the screen and then add them into a MySQL database.
I need to use the JavaScript variable selectedVisibleValue that is defined in my first function dbQuery The reason I want to do this is because I have four drop downs, three of which are hidden drop downs that are only shown depending on the first non hidden dropdown, only one of the hidden drop downs is ever visible.
I want to work with these variables in my PHP page formPage to do the Database functions. My code is below I want to add the testing1 function into the dbQuery function.
I have tried just copying and pasting it into the dbQuery function but it does not work. I am not trying to work with the selectedVisibleValue in the code below. I am just trying to do some testing with some bogus variables.
var dbQuery = function(){
var description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
var selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
var selectedVisibleValue = $(".unitDropDowns select:visible").val();
document.getElementById("descriptionSummary").innerHTML = "<h3>Description</h3>" + "<p>" + description + "</p>";
document.getElementById("equipmentRan").innerHTML = "<h3>Equipment Ran </h3>" + "<p>" + selectedEquip1 + "</p>" + "<h3>Unit Number</h3>" + "<p>" + selectedVisibleValue + "</p>";
document.getElementById("equipmentRan").style.display = "block";
document.getElementById("descriptionSummary").style.display = "block";
}
var testing1 = function() {
$.get(
"formPage.php",
{paramOne : 123, paramX : 'abc'},
function(data) {
document.getElementById("equipmentRan").innerHTML = ('page content: ' + data);
}
);
}
//cache references to static elements
var jobDescription = $('#jobDescription')
, selectedEquip = $('#equipmentList')
, descriptionSummary = $('#descriptionSummary')
, equipmentRan = $('#equipmentRan')
;
function dbQuery(){
//gather params
var params = {
jobDescription : jobDescription.val(),
selectedEquip1 : selectedEquip.val(),
selectedVisibleValue = $(".unitDropDowns select:visible").val()
}
//show summary
descriptionSummary.html('<h3>Description</h3><p>'+description+'</p></h3>').show();
equipmentRan.html('<h3>Equipment Ran</h3><p>'+selectedEquip1+'</p><h3>Unit Number</h3><p>'+selectedVisibleValue+'</p>').show();
//do a get
$.get('formPage.php',params,function(data) {
equipmentRan.html('page content: ' + data);
}
}
jsFiddle DEMO
Passing variables between functions might come in useful for your project.
HTML:
<div id="theBox"></div>
<button>Press Me</button>
JS
$(document).ready(function() {
// This is some other Do More function, defined prior to the next variable function.
// This is your .get() request.
function doMore(target){
// For the incomming targer, add a class style of a larger font.
$(target).css('font-size', 30);
}
// The main function.
var dbQuery = function() {
// Show dynamic text on the HTML page.
var extra = $('#theBox').html('Dynamic Text Results');
// Run some other function, also... send the private variable in use.
doMore(extra);
};
// The submit button.
$('button').on('click', function() {
// Start the function.
dbQuery();
});
});
Here is the working code:
function dbQuery() {
window.description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
window.selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
window.selectedVisibleValue = $(".unitDropDowns select:visible").val();
testing1();
}
function testing1() {
$(document).ready(function() {
$.get(
"formPage.php",
{paramOne : window.selectedVisibleValue, paramX : window.description, paramY : window.selectedEquip1},
function(data) {
document.getElementById("equipmentRan").innerHTML = (data);
}
);
});
}

Categories