I am trying to link my website to a Parse server using mongodb. It was running well, and saving so i could see in parse dashboard, and mlab. I attempted to add a new variable which resulted in me messing something up. When this get run it throws an error saying address is not defined on the line with Parse.Cloud.run.
document.getElementById("btn").addEventListener("click", function(){
var name = document.getElementById('inp1').value;
var address = document.getElementById('inp2').value;
var city = document.getElementById('inp3').value;
var state = document.getElementById('inp4').value;
var zipcode = document.getElementById('inp5').value;
var Apartment = Parse.Object.extend("Apartment");
var apartment = new Apartment();
apartment.set("name", name);
apartment.set("address", address);
apartment.set("city", city);
apartment.set("state",state);
apartment.set("zipcode", zipcode);
apartment.save(null, {
success: function(apartment) {
// Execute any logic that should take place after the
object is saved.
alert('New object created with objectId: ' + prod.id);
},
error: function(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);
}
});
});
Parse.Cloud.run("registerApartment",{"name":name,"address":address,"city":
city, "state": state,"zipcode":zipcode,"map":map}, {
success: function(savedApartment){
console.log(savedApartment);
}, error: function(error){
console.log(error);
}
})
thank you ahead of time!
cloud code
Parse.initialize('#');
Parse.serverURL = 'http://localhost:1337/parse';
Parse.Cloud.define("registerApartment", function(req,res){
var params = request.params;
var name = params.name;
var address = params.address;
var city = params.city;
var state = params.state;
var zipcode = params.zipcode;
var Apartment = Parse.Object.extend("Apartment");
var apartment = new Apartment();
apartment.set("name", name);
apartment.set("address", address);
apartment.set("city", city);
apartment.set("state",state);
apartment.set("zipcode", zipcode);
apartment.set("map", map);
console.log(apartment);
apartment.save(null, {
success: function(savedApartment){
console.log("Succesfully saved bitch");
response.success(savedApartment);
}, error: function(error){
console.log(error);
response.error(error);
}
})
});
could you double check your server where you define the cloud code?
Your code should be something along this line:
Parse.Cloud.define("registerApartment", function(req,res){
---your codes---
});
Make sure that your Parse.Cloud.run() is calling what you defined back at your server.
Edit:
Try to use this code instead of your current one:
Parse.Cloud.run("registerApartment",{name:name,address:address,city:
city, state: state,zipcode:zipcode,map:map}, {
success: function(savedApartment){
console.log(savedApartment);
}, error: function(error){
console.log(error);
}
})
All i did was remove the quotes when parsing in a parameter. This should work fine :)
Related
I am using the new open source parse server and this is what I have in the main.js for creating a object.
Parse.Cloud.define("purchaseItem", function(request, response) {
Parse.Cloud.useMasterKey();
var order, custom;
Parse.Promise.as().then(function() {
var fullreceipt;
var receiptData = new Array();
receiptData = request.params.receipt.titles;
if(receiptData){
console.log('value of recept data is good');
}
if (!receiptData){
console.log('Value of receiptData is empty');
}
for (var i = 0; i < receiptData.length; i++) {
console.log(receiptData[i]);
fullreceipt = receiptData[i];
console.log(fullreceipt);
//Do something
}
var currentUser = Parse.User.current();
order = new Parse.Object('Order');
order.set('name', request.params.name);
order.set('email', request.params.email);
order.set('address', request.params.address);
order.set('zip', request.params.zip);
order.set('city_state', request.params.city_state);
order.set('fulfilled', false);
order.set('charged', false); // set to false until we actually charge the card
order.set('user', currentUser);
order.set('receipt', request.params.receipt);
order.set('tipAmount', request.params.tipAmount);
order.set('taxAmount', request.params.taxAmount);
order.set('orderInstructions', request.params.instructions);
order.set('pickupOrDelivery', request.params.pickupOrDelivery);
order.set('totalBillAmount', request.params.totalBill);
return order.save().then(null, function(error) {
console.log('Creating order object failed. Error: ' + error);
return Parse.Promise.error('An error has occurred. Your credit card was not charged.' + order);
});
}
}
In the logs I get value of recept data is good but creating the object fails and I get the error message, Creating order object failed. Error: [object Object]
. If any one cloud help that would be great!
I looks like found my own answer in a error message. What was going wrong was I need to point it to the new parse server on AWS api and not the old parse api.
I'm trying to make a connection of two classes in Parse.com via Pointer.
I have one class which is called magazia and I put some rows inside.
Also I have a class which is called "Events" which has a magaziaid column which is Pointer to class magazia.
I want to make a post in Events with a specific objectId of the other class ("magaziaid") from a form.
So I have this code for now:
function saveJobApp(objParseFile) {
var jobApplication = new Parse.Object("events");
var name = document.getElementById('name').value;
var description = document.getElementById('description').value;
var magaziid = "2xOhgyX0BU";
jobApplication.set("image", objParseFile);
jobApplication.set("name", name);
jobApplication.set("description", description);
jobApplication.set("magaziaid", this.magaziid.id); //breakpoint
jobApplication.save(null, {
success: function(gameScore) {
},
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);
}
});
//var objectId = jobApplication.getObjectId();
// objectId = document.getElementById("objID").innerHTML;
// console.log(objectId);
}
$('#submitId').on("click", function(e) {
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
console.log("Done");
parseFile.save().then(
function() {
saveJobApp(parseFile);
},
function(error) {
alert("error");
}
);
});
});
That i'm trying to put the objectId copied from the "magazia" class, but i get an error, "Failed to create object with error code: Undefined"
What is my mistake here?
How can i pass the object id of a row from "magazia" class and put it on the pointer of the class "events" ???
Thanks in advance!
Update 1. in //breakpoint i have also tried those different codes
jobApplication.set("magaziaid", {__type: "Pointer", className: "events", objectId: magaziid});
and this one
jobApplication.set("magaziaid", magaziid);
Your pointer value should be a magazia object and not an id. Do the following and it should work.
var magaziaObject = new Parse.Object("magazia");
// add anything you want to magaziaObject
// like magaziaObject.id, magaziaObject.name, etc.
// and then save the magaziaObject in your events (jobApplication) object
jobApplication.set("magaziaid", magaziaObject);
What if I have an array of events that I want users to be able to rsvp for? Essentially needing the data of the "user" who clicked "rsvp", and the "title" of the "event" that they've rsvp'd for. Could I make a pointer in a Agree class that includes the user's name/id and another pointer that includes the title of the event rsvp'd for? Is there a way to somehow use Angular to add code to the "Agree" class with a form?
User Class:
objectId
username
password
Agree Class:
objectId
username-(current user)
Comments Structure:
Event Class:
objectId-
title-(Need this title)
description-
date-
Please help me understand how to make this work..Thanks!
$scope.getAgree = function(){
var Agree = Parse.Object.extened("Agree");
var query = new Parse.Query("Agree");
query.include("userName");
query.find().then(function(results){
//Go through each in Array
var rsvpOjectArray = new Array();
or(i in results){
//Set Object to current RsvpObject
var obj = results[i];
//Get user
var userName = obj.get("userName").get("username");
rsvpOjectArray.push({
user: {userName
}
});
}
});
};
$scope.makeAgree = function(){
var Agree = Parse.Object.extend("Agree");
var agree = new Agree();
var user = new Parse.Object("Agree");
agree.set("userName", Parse.User.current());
agree.save(null, {
success: function(rsvp) {
// Hooray! Let them use the app now.
alert("success!");
},
error: function(rsvp, error) {
// Show the error message somewhere and let the rsvp try again.
alert("Error: " + error.code + " " + error.message);
}
});
};
As documentation says - "The JavaScript SDK does not currently support modifying Installation objects.", but what about creating these objects? is it possible to create Installation objects from cloud code?
For ex:
Parse.Cloud.define("registerForNotifications", function(request,response) {
var token = request.params.deviceToken;
var deviceType = request.params.deviceType;
var user = request.user;
var installation = new Parse.Object("Installation");
if (installation) {
installation.set("deviceToken",token);
... so on..
installation.save();
}
});
Will this work? Thank you.
Some example:
//The following Cloud Function expects two parameters: the channel to be added to this user's installations, and the object id for the user.
//It assumes that each installation has a `Pointer <_User>` back to the original user.
//...
Parse.Cloud.define("subscribeToChannel", function(request, response) {
var channelName = request.params.channel;
var userId = request.params.userId;
if (!channelName) {
response.error("Missing parameter: channel")
return;
}
if (!userId) {
response.error("Missing parameter: userId")
return;
}
// Create a Pointer to this user based on their object id
var user = new Parse.User();
user.id = userId;
// Need the Master Key to update Installations
Parse.Cloud.useMasterKey();
// A user might have more than one Installation
var query = new Parse.Query(Parse.Installation);
query.equalTo("user", user); // Match Installations with a pointer to this User
query.find({
success: function(installations) {
for (var i = 0; i < installations.length; ++i) {
// Add the channel to all the installations for this user
installations[i].addUnique("channels", channel);
}
// Save all the installations
Parse.Object.saveAll(installations, {
success: function(installations) {
// All the installations were saved.
response.success("All the installations were updated with this channel.");
},
error: function(error) {
// An error occurred while saving one of the objects.
console.error(error);
response.error("An error occurred while updating this user's installations.")
},
});
},
error: function(error) {
console.error(error);
response.error("An error occurred while looking up this user's installations.")
}
});
});
I was wondering what the order of operations are in the parse cloud. I currently am running into trouble trying to do multiple things at once inside my job on the cloud. I am currently trying to make an HTTP request for each user in my user table (there are 2) and then get the webpage or httprequest.text from the webpage. My code is as followed
Parse.Cloud.job("WeatherUpdates2", function(request, status) {
var query = new Parse.Query(Parse.User);
query.exists("City");
query.each(
function(result){
var object = result;
console.log(object.id);
var city = object.get("City");
city = city.replace(" ", "");
city = city.replace(" ", "");
// get the country code.
var countryCode = object.get("CountryCode");
var woeidUrl = "http://where.yahooapis.com/v1/places.q(" + city + "," + countryCode + ")?appid=(appid)";
console.log(woeidUrl);
var woeID = "An error occured retrieving your WOEID.";
Parse.Cloud.run('httpRequest', { url: woeidUrl }, {
success: function(WOEID) {
console.log("returned from http request.");
},
error: function(error) {
console.log("Error occurred while making request for WOEID " + error.message);
status.error(error.message);
}
});
},
{
success: function() {
// results is an array of Parse.Object.
console.log('#Query');
status.success("Updated Records!!");
},
error: function(error) {
// error is an instance of Parse.Error.
console.log('#error');
response.error("Failed to save vote. Error=" + error.message);
}
});
});
Where the job httpRequest is:
Parse.Cloud.define("httpRequest", function(request, response) {
var webpage = "Something went wrong.";
Parse.Cloud.httpRequest({
url: request.params.url,
success: function (httpResponse) {
webpage = httpResponse.text;
webpage = webpage.toString();
response.success(webpage);
},
error: function (error)
{
console.log("Error in http request " + error.message);
response.error(error.message);
}
});
});
now I would expect to be printed would be the, object id of first user, their url, the job running, the message"returned from http request." then repeated another time for the second user and finally the job finishing with the message "Updated Records". but instead I get:
I2014-07-22T15:15:16.013Z] A5hod7qKE3
I2014-07-22T15:15:16.045Z] http:/where.yahooapis.com/v1/places.q(Draper,US)?appid=(appid)
I2014-07-22T15:15:16.053Z] GmuqxpTUpM
I2014-07-22T15:15:16.066Z] http:/where.yahooapis.com/v1/places.q(SaltLakeCity,US)?appid=(appid)
I2014-07-22T15:15:16.082Z] #Query
I2014-07-22T15:15:16.131Z] v385: Ran cloud function httpRequest with:
Input: {"url":"http://where.yahooapis.com/v1/places.q(SaltLakeCity,US)?appid=(appid)"}
Result:
2487610TownSalt Lake CityUnited StatesUtahSalt LakeSalt Lake City40.777561-111.93071740.699890-112.10125740.852951-111.739479511America/Denver
I2014-07-22T15:15:16.141Z] v385: Ran cloud function httpRequest with:
Input: {"url":"'http://where.yahooapis.com/v1/places.q(Draper,US)?appid=(appid)'"}
Result:
http://where.yahooapis.com/v1/schema.rng'" xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:start="0" yahoo:count="1" yahoo:total="11">2393601TownDraperUnited StatesUtahDraper8402040.524139-111.86627240.442921-111.92212740.544361-111.78304349America/Denver
I removed 1 / from both the printing urls so I could posts this because I don't have high enough rep to post more than 2 links. I also have put in my appid into the (appid) so the url does return to me the according woeid from yahoo.com. The problem here being I can't actually get into the success function of the http request job. Any help is greatly appreciated!
EDIT:
I was trying to figure out how to run a job in a for loop but couldn't get it to work. I tried to make a promise and do what Fosco said below, but have had no luck. Here is my code.
for(var i = 0; i < woeIDs.length; i++)
{
console.log("hello");
var weatherURL = "http://weather.yahooapis.com/forecastrss?w=" + woeIDs[i] + "&u=f";
var promise = Parse.Cloud.run('httpRequest', { url: weatherURL }, {
success: function(WOEID) {
console.log("got here");
},
error: function(error) {
console.log("Error occurred while making request for WOEID " + error.message);
status.error(error.message);
}
});
Parse.Promise.when([promise]).then(function() { status.success(); });
}
if I run this code I get a hello twice then the two job calls then the "got here" message once. I have tried adding a return statement to it and with no luck also. Thanks again for all the help!!!
The issue here is that inside the each callback, you need to return the promise from your cloud function call if you want to ensure the tasks complete, and have it wait before going to the next object.
Simplified and using promises:
query.each(function(object) {
...
return Parse.Cloud.run(...);
}).then(function() {
// success
}, function(err) {
// error
});
For looping over a promise-returning function like Parse.Cloud.run:
var promises = [];
for (i = 0; i < 5; i++) {
promises.push(Parse.Cloud.run('...', {}));
}
Parse.Promise.when(promises).then(function() {
// all done
}, function(err) {
// error
});