I am trying to upload a picture as well as some other data, which is captured from a form, to my Parse database. A lot of this code is copied from the Parse Javascript guide. The name, price and description details upload fine, but the picture never uploads. What I get on my log is:
adding item...
Item sucessfully added!
Item sucessfully uploaded!
In that order... I'm not sure why this would happen especially since i'm using the whole promise paradigm. Why would the item be added before the image is uploaded? And why isn't this code working?
function addItem()
{
console.log('adding item...');
var Item = Parse.Object.extend("FoodItem");
var newItem = new Item();
newItem.set("createdBy", Parse.User.current());
newItem.set("name",$('#itemName').val());
newItem.set("price",parseInt($('#itemPrice').val()));
newItem.set("description",$('#itemDescription').val());
//Upload pic to parse cloud
var fileUploadControl = $("#itemImage")[0];
if (fileUploadControl.files.length > 0)
{
var file = fileUploadControl.files[0];
var name = "photo.jpg";
var parseImage = new Parse.File(name, file);
}
parseImage.save().then
(
function()
{
newItem.set(name,parseImage);
console.log("Image sucessfully uploaded!");
return;
}
).then
(
newItem.save().then
(
function()
{
console.log("Item sucessfully added!")
},
function(error)
{
// there was some error.
alert("Saving item failed with error code " + error.message);
}
)
);
return false;
}
.then() takes functions as arguments. In your second .then() you want to pass a function to be called when the promise is resolved. Instead you are actually calling the function and passing the results to then.. so that function gets called before the first promise resolves. Also, you should return a promise from your first .then(). I think the following should work:
parseImage.save().then(function() {
newItem.set(name,parseImage);
console.log("Image sucessfully uploaded!");
return newItem.save();
})
.then(function() {
console.log("Item sucessfully added!")
},
function(error) {
// there was some error.
alert("Saving item failed with error code " + error.message);
});
Related
May be I am not asking it in right way. I am kind of new on Tizen.
Here is my code set for tizen.
respons = tizen.filesystem.resolve("documents", function(dir)
{
file = dir.resolve("myfile.txt");
if(file.isFile){ //if file is present then fetch the information.
var res_one = file.openStream("r",
function(fs) {
var my_json = JSON.parse(fs.read(file.fileSize));
fs.close();
res_two = my_json.json_value;
return res_two;
},
function(e) {
console.log("Error " + e.message);
return null;//if there is any error then return null
}, "UTF-8");
return res_one;
}
else{
return null; //if file is not present then return null
}
});
Basically I have a file present on my display(Installed Tizen OS) that contains a json:
json_value: "My Information"
I am trying to fetch the information to use that in my javascript code. I am able to fetch that information(Checked using console.log). But it is not being returned in res_one or in response.
In short form I want to access that json outside tizen.filesystem.resolve( ...
Thanks in advance.
I have done it. Basically this is asynchronous behaviour of javascript so I have done it using call back.
function to_fetch_the_value_and_chain_process(passed_function){
tizen.filesystem.resolve("documents", function(dir){
file = dir.resolve("myfile.txt");
if(file.isFile){ //if file is present then fetch the information.
var res_one = file.openStream("r",
function(fs) {
var my_json = JSON.parse(fs.read(file.fileSize));
fs.close();
res_two = my_json.json_value;
passed_function(res_two);
},
function(e) {
console.log("Error " + e.message);
passed_function(null);;//if there is any error then return null
}, "UTF-8");
return res_one;
}
else{
passed_function(null); //if file is not present then return null
}
});
}
funtion passed_function(retrieve_res_two){
alert(retrieve_res_two );
//use retrieve_res_two and chain the next code here.....
}
to_fetch_the_value_and_chain_process(passed_function);
I know there were similiar questions, but I see no solution in them.
I want to create new object if it doesn't exists in database, and update if one exists.
Here is my simple code :
Parse.Cloud.beforeSave("Tag", function(request, response) {
var query = new Parse.Query("Tag");
query.equalTo("name", request.object.get("name"));
query.first({
success: function(result) {
if (!result) {
response.success();
} else {
result.increment("popularityCount");
result.save();
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
});
As you see, I am calling it beforeSave. If query doesn't find anything, creates new entry. If query finds something, it should take this result, and popularityCount. But it doesn't. It works only if I call response.success() after that, but calling this function causes also in creating new entry.
It seems wrong to increment a counter on an object on every save. What if the object is modified for some other reason? If you really do want to increment a field on every save, there's no need for a query -- the object being saved is passed to the function. Moreover, a query will not work in the case where a new object is being saved.
How about instead, find or create the object as one operation, increment the counter when app logic calls for it
function findOrCreateTagNamed(name) {
var query = new Parse.Query(Tag);
query.equalTo("name", name);
return query.first().then(function(tag) {
// if not found, create one...
if (!tag) {
tag = new Tag();
tag.set("popularityCount", 0);
tag.set("name", name);
}
return (tag.isNew())? tag.save() : Parse.Promise.as(tag);
});
}
function incrementPopularityOfTagNamed(name) {
return findOrCreateTagNamed(name).then(function(tag) {
tag.increment("popularityCount");
return tag.save();
});
}
Now there's no need for beforeSave logic (which seems like the right thing to do, not a workaround).
Parse.Cloud.beforeSave("Tag", function(request, response) {
var tag = request.object;
tag.increment("popularityCount");
response.success();
});
How do I save a user pointer to an object when i have the object id of the user.
I am able to save the object to the class in Parse but the assignee is always 'Undefined' in Parse.
e.g. I have retrieved the user object and can get the username / object id etc through:
function getUserFromUsername(username) {
Parse.initialize("...", "...");
console.log('The username passed in is: ' + username);
var User = Parse.Object.extend("_User");
var query = new Parse.Query(User);
query.equalTo("username", username);
query.first({
success : function(result) {
// Do something with the returned Parse.Object values
var userPointer = new Parse.User();
userPointer = result;
console.log(userPointer.get('username')); // this returns the correct username
return userPointer;
},
error : function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
Which is called from my save task function below: (Note, I've logged all relevant fields and they return as expected.
function saveNewTask(clientName, taskTitle, taskDue, assigneeArray) {
Parse.initialize("...", "...");
var x;
for (x in assigneeArray) {
var Task = Parse.Object.extend("Tasks");
var task = new Task();
task.set("title", taskTitle);
task.set("date", taskDue);
var thisAssignee = GetUserFromUsername(assigneeArray[x]);
task.set('assignee', thisAssignee);
task.save(null, {
success : function(task) {
// Execute any logic that should take place after the object is saved.
console.log('New object created with objectId: ' + task.id);
},
error : function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
console.log('Failed to create new object, with error code: ' + error.message);
}
});
}
}
So you should save a pointer to the user to the task.
var Task = Parse.Object.extend("Tasks");
var task = new Task();
task.set("user", user);
task.set("title", "taskTitle");
task.set("date", taskDue);
task.save(null, {
success : function(task) {
// Execute any logic that should take place after the object is saved.
console.log('New object created with objectId: ' + task.id);
},
error : function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
console.log('Failed to create new object, with error code: ' + error.message);
}
});
By default, when fetching an object, related Parse.Objects are not fetched. These objects' values cannot be retrieved until they have been fetched like so:
var user = task.get("user");
user.fetch({
success: function(user) {
//fetch user is here
}
});
This is explained here: https://parse.com/docs/js_guide#objects-pointers
The problem with your script is when you are querying in Parse it is done asynchronously so you can't return the user immediately. Instead you need to return the promise and then handle it when you call getUserFromUsername:
function getUserFromUsername(username) {
var User = Parse.Object.extend("_User");
var query = new Parse.Query(User);
query.equalTo("username", username);
return query.first();
}
getUserFromUsername('testUsername').then(function(result) {
//use User here
}, function(error) {
alert("Error: " + error.code + " " + error.message);
});
Take a look at this document on promise chaining for more information about promises:
I'm using JavaScript and parse.com
The below code is not returning any errors in the console log and is creating a new object in parse.com as expected (Under myBadges). But for some reason "BadgeName" is not being captured and is showing as "undefined".
The "BadgeName" column should be populated from the "badgeselected" variable. But "BadgeName" does not appear to being captured as a variable?
Can anyone help me understand why this is happening?
Here is a screen shot of the parse.com backend.
var badgeselected = $("#go").attr("src");
var MyBadges = Parse.Object.extend("myBadges");
var userbadges = new MyBadges();
$(document).ready(function () {
$("#send").click(function () {
userbadges.set("BadgeName", badgeselected);
console.log("done");
userbadges.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);
}
});
});
});
Your first line, var badgeselected = $("#go").attr("src");, must also exist inside the $(document).ready callback.
The entire point of that callback is to ensure that the DOM is ready for you to access it. You've put some of your DOM-accessing code inside the callback, but not all of it.
I would have expected the following parse.com/javascript code block to save the selected "badeselected" variable to the parse class "myBadges" and automatically create a relationship back to the "_USer" class.
There are no errors being returned in the console log, however neither are there any records being added to the "myBadges" class.
I'm not sure what error I've made here?
Parse.initialize("XXXXX", "XXXXX");
var badgeselected = $("#go").attr("src")
var contact = Parse.Object.extend("myBadges");
var contact = Parse.User.current();
$(document).ready(function () {
$("#send").click(function () {
contact.set("BadgeName", badgeselected);
console.log("done");
contact.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);
}
});
});
});
You are declaring contact twice. First as an extension called myBadges, and then as current user (discarding the first). Check the current user object in the data browser. You should find the badges there.
UPDATE
Here is an example from the javascript guide:
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.set("score", 1337);
gameScore.set("playerName", "Sean Plott");
gameScore.set("cheatMode", false);
gameScore.save(null, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id);
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
You should be able to use this in your jquery code. See how they first declare GameScore as an extension, and then gameScore as new GameScore();
And THEN they set the values on the object.
More info: https://parse.com/docs/js_guide