Parse create user example not working - javascript

I'm trying to make a registration screen for a new web project I'm working on. It didn't seem to be working so I tried out just using the basic create user example on Parse.com
function register()
{
var user = new Parse.User();
user.set("username", "my name");
user.set("password", "my pass");
user.set("email", "email#example.com");
user.signUp(null, {
success: function(user) {
// Hooray! Let them use the app now.
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
}
Every time the call gets made I get this error...
Any ideas would be gratefully appreciated.
Thanks

You can find the specifics about Error codes for Parse here : https://www.parse.com/docs/js/guide#errors
100 is "ConnectionFailed". Seems like you (or at least your app ^^) has a problem connecting to Parse servers...
Hope it helps.
(on another note, you should edit your first post instead of answering if you want to add infos, follow-ups etc to your question ;) )

Just checked the database... turns out it was working but still throwing the error state. Guess I just have to check specific errors for now

Related

I'm trying to integrate Intercom into a meteor app using verso:intercom

Ok, so I've integrated it and it's working fine at a basic level but I have 2 related problems....
Firstly, where do I put this code
IntercomSettings.userInfo = function(user, info) {
// add properties to the info object, for instance:
if (user.services.google) {
info.email = user.services.google.email;
info['Name'] = user.services.google.given_name + ' ' + user.services.google.family_name;
}
}
in order to get the info of users logged into say, Google? Can I do the same with FB, LinkedIn etc?
Secondly, how do I get the info of users logged into my app sent to intercom? (I'm getting the userId , location, last page visited)
Many thanks in advance.
So, I got this sorted. Put the following in client/lib/main.js....
IntercomSettings.userInfo = function(user, info) {
info.email = Meteor.user().emails[0].address;
info['name'] = Meteor.user().username;
};

Get custom attribute from User class on Parse.com [JavaScript]

I'm working on a website with Parse.com and JavaScript. I have my "User" class, but I have added more fields than those that come by default.
I want to get one specific attribute from my User class (IdGroup) when user logs in, so I'm trying to capture the IdGroup using user object when login has been succesfully.
I have tried this:
Parse.User.logIn(username, pass, {
success: function (user) {
//var idGroup = user.get("IdGroup");
localStorage.setItem("parseUser", true);
localStorage.setItem("guestUser", false);
localStorage.setItem("username", username);
user.fetch().then(function (fetchedUser) {
var idGroup = user.get("IdGroup");
localStorage.setItem("IdGroup", idGroup);
});
window.location.href = 'index.html';
},
error: function (user, error) {
alert('Invalid username or password!');
}
});
This doesn't work.
If anyone could give me a hand, I will really appreciate.
Thanks!!
I would have assumed that the user was already fetched at login.
But your callback function passes in the object fetchedUser, and you're accessing the user object. So, var idGroup = fetchedUser.get("IdGroup"); is probably what you're looking for.

Why is my client-side save function firing multiple times?

There are a lot of things going on here, so I'll try to run the line between being brief and being fully descriptive.
Overall goal: I'm creating a barebones (no CSS) admin panel that interfaces with a Parse.com NoSQL/MongoDB database, using HTML forms and Backbone.js to control the communication and save user-inputted information into the Parse database. I am not performing any validation other than some basic stuff client side.
Background: For one specific task, I am doing two things: 1) Grabbing information from Parse.com's database on "page load" (not EXACTLY at page load, but I am not certain how to render the view correctly without doing this - when the user selects the "add purchase" option, the addPurchase View is generated, and I make form submit once with a 0 value to query the database and append the results to the screen - I think this may be causing the issue) and using jQuery to render the information to the HTML page. 2) Then, I am asking the user to select one of 4 options, upon submission of which I will record this as a transaction and generate an entry in a "purchase log" table also with Parse.com.
The problem: The view renders successfully, and the values are successfully retrieved from the database and placed on the page. However, when the user submits the form indicating which option they choose, the resulting transaction record is being stored in the database at a rate of some function of 'n', where n is the number of times a transaction record has already been saved in the current session. If I refresh the view, the 'n' resets. The more times I save without refreshing the page, the more duplicate entries are saved.
I'm new to BackboneJS, Parse.com, and MV* frameworks in general. So I definitely think my code could use some cleanup, and I also feel like I'm missing a key piece of information about how Backbone/HTML forms/Views/the DOM works. So I apologize in advance for any sloppy code; I'm totally cool with any suggestions for cleanup you have as well =P.
My Code: There are a number of places where something could be going wrong, I'll try to keep it succinct.
In the HTML, I have a set of radio buttons that allows the user to decide what action they want to perform. Depending on which button is selection, different forms will render to the browser. Once a form is submitted, Parse attempts to save the values in the database and upon successful save, calls back to the browser with an alert saying save was successful, and then a new AdminPanelView() is called.
The problem of multiple saves happened with other actions too, but I solved the problem by adding the following two lines immediately after the save function:
this.undelegateEvents();
delete this;
However, when I do that inside the query's success block in the addPurchase function, I get a console error telling me that undelegateEvents() is not a function of 'this', and the debugger tells me that 'this' is assigned to the Window at the time this call is made.
If I try to move those same two lines to just after the query function as well, it appears that nothing gets saved at all. The view just immediately switches back to a fresh AdminPanelView, without saving.
The behavior also changes depending on where I put 'return false' statements throughout the addPurchase function, but I haven't been able to figure out exactly what the returns are doing and I've just been playing whack-a-mole with them without really understanding what is happening in the code.
Please help me figure out what I'm doing wrong here! I feel like I'm misunderstanding a core concept here, so I'm eager to find out what it is and learn more about how Backbone and Parse works.
The behavior of the form is governed by some Backbone code:
var AdminPanelView = Parse.View.extend({
events: {
"click form.manageOperations": "manageOperations",
"submit form#newPurchaseInfo": "addPurchase",
//other stuff too
},
el: ".content",
initialize: function(){
this.render();
_.bindAll(this, "manageOperations", "addPurchase");
this.manageOperations();
},
render: function(){
this.$el.html(_.template($("#admin_panel_template").html()))
this.delegateEvents();
},
manageOperations: function()
{
this.$(".inputInfo").hide();
var v = this.$("input[name=defineOperation]:checked").val();
if (v=="add-purchase") { this.$("#newPurchaseInfo").show();
this.$("#newPurchaseInfo").submit();}
else if //cases for the other options - normally I just
call this.$("#new[Whatever]Info.show();
},
addPurchase: function() {
var Perk = Parse.Object.extend("Perk");
var query = new Parse.Query(Perk);
query.find({
success: function(results)
{
var i = 1;
for (var r in results)
{
this.$("#perk"+i+"co").html(results[r].get("company"));
this.$("#perk"+i+"desc").html(results[r].get("description"));
i++;
}
var purchase = Number(this.$("#newPurchaseInfo .perkChoice").val());
// I think this line may be causing the issue.
if (purchase!=0)
{
alert("you indicated you want to use perk # " + purchase +", "
+ "which indicates " + results[purchase-1].get("description")
+ " from " + results[purchase-1].get("company"));
var Purchase = Parse.Object.extend("PurchaseLog");
var purchaseEntry = new Purchase();
user = Parse.User.current();
purchaseEntry.save(
{
info : info,
}, {
success: function(purchase)
{
alert("purchase saved successfully");
new AdminPanelView();
return false;
},
error: function(purchase, error)
{
alert("purchase NOT saved: code " + error.code + ", " + error.message);
}
});
}
return false;
},
error: function(error)
{
alert("error code " + error.code + ": " + error.message);
}
});
// this.undelegateEvents();
// delete this;
return false;
},
Actually, I just figured it out. I love stackoverflow, sometimes just writing the problem description is enough to find the solution! If only I didn't answer my own questions so much, I would have more reputation =P
So, the problem was indeed within my addPurchase function(code highlighted below). What was happening is that the addPurchase view was always instantiated with an initial value of 0 being submitted in order to render the screen. However, as I was doing it defore, the 'this.undelegateEvents()' and 'delete this' were being called on the initial submit regardless. So I was basically deleting the views functionality without fully deleting the view until I tried to submit the form again, at which point I would get an entirely new AdminPanelView() and no save message (the value never saved because the submit value was 0, meaning the save() function was never called).
I simply made it so that the 'this.undelegateEvents()' and 'delete this' methods ONLY get called if the input value is NOT 0. Because in my program logic (however stupid it may be =P), 0 would only be input upon rendering the addPurchase view, in order to render the Perk information to the DOM.
I still feel like my code is convoluted as shit, and I'm open to suggestions on better algorithms, logic, and structure. Part of it is difficult because database return values are only in scope in the success() blocks of the Parse and Backbone functions, so a certain amount of "wall of doom" is hard to avoid.
query.find({
success: function(results)
{
var purchase = Number(this.$("#newPurchaseInfo .perkChoice").val());
if (purchase!=0) {
// attempt to save user in database
purchaseEntry.save(
{
//definition of the object goes here
}, {
success: function(purchase)
{
alert("purchase saved successfully");
new AdminPanelView();
return false;
},
error: function(purchase, error)
{
alert("purchase NOT saved: code " + error.code + ", " + error.message);
}
});
}
return false;
},
error: function(error)
{
alert("error code " + error.code + ": " + error.message);
// return false;
}
});
//This is the solution:
if (Number(this.$("#newPurchaseInfo .perkChoice").val()) != 0)
{
this.undelegateEvents();
delete this;
}
return false;

Parse Cloud Code Sending Push Notification Twice

I am trying to send a push notification using cloud code to targeted channels. The Object is called Prayers. When someone saves Prayers, it is supposed to send a push notification to certain channels, if the new data in Prayers was not made anonymously. Prayers has a key of 'Anonymous' in it that is boolean. So, I have cloud code set up like this, in an effort that if the boolean value is false, it sends, it, but if it is true, it won't send the push. The issue now is that it is sometimes sending the Push through 2 times on a non-anonymous post.
Parse.Cloud.afterSave("Prayers", function(request) {
var firstName = request.object.get('FirstName');
var lastName = request.object.get('LastName');
var userId = request.object.get('UserId');
var anonymous = request.object.get('Anonymous');
var anonymousString = anonymous.toString
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo('channels', userId);
if (anonymous == false) {
Parse.Push.send({
where: pushQuery, // Set our Installation query
data: {
alert: firstName + " " + lastName + " " + "just added a prayer request."
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
throw "Got an error " + error.code + " : " + error.message;
}
});
}
});
At first glance there doesn't seem anything wrong with your function, but since you always try to send a push notification after a prayer has been saved, are you sure you're not saving the object twice? That could be the reason why the afterSave is invoked twice.
One of the things I also once ran into was, that I had 2 pieces of cloud code
First one would modify an object when I tried to save it.
Second one was that I would do a push after saving the object.
In my code where I modified the object during the save process, I saved the modified object, which resulted in my Parse.Cloud.afterSave being fired twice for the same object
Server Side
Update reg_id by UUID when device registration on server.
Delete by reg_id which have return a canonical_id in the response after send a push.
Periodically send fake push using dry_run and do the same things as 2.
Client Side
Send message_id within payload, and save it in sqlite DB. And device will know that it has received it or not.

What would cause "Request timed out" in parse.com cloud code count?

One of my cloud functions is timing out occasionally. It seems to have trouble with counting, although there are only around 700 objects in the class. I would appreciate any tips on how to debug this issue.
The cloud function works correctly most of the time.
Example error logged:
E2015-02-03T02:21:41.410Z] v199: Ran cloud function GetPlayerWorldLevelRank for user xl8YjQElLO with:
Input: {"levelID":60}
Failed with: PlayerWorldLevelRank first count error: Request timed out
Is there anything that looks odd in the code below? The time out error is usually thrown in the second count (query3), although sometimes it times out in the first count (query2).
Parse.Cloud.define("GetPlayerWorldLevelRank", function(request, response) {
var query = new Parse.Query("LevelRecords");
query.equalTo("owner", request.user);
query.equalTo("levelID", request.params.levelID);
query.first().then(function(levelRecord) {
if (levelRecord === undefined) {
response.success(null);
}
// if player has a record, work out his ranking
else {
var query2 = new Parse.Query("LevelRecords");
query2.equalTo("levelID", request.params.levelID);
query2.lessThan("timeSeconds", levelRecord.get("timeSeconds"));
query2.count({
success: function(countOne) {
var numPlayersRankedHigher = countOne;
var query3 = new Parse.Query("LevelRecords");
query3.equalTo("levelID", request.params.levelID);
query3.equalTo("timeSeconds", levelRecord.get("timeSeconds"));
query3.lessThan("bestTimeUpdatedAt", levelRecord.get("bestTimeUpdatedAt"));
query3.count({
success: function(countTwo) {
numPlayersRankedHigher += countTwo;
var playerRanking = numPlayersRankedHigher + 1;
levelRecord.set("rank", playerRanking);
// The SDK doesn't allow an object that has been changed to be serialized into a response.
// This would disable the check and allow you to return the modified object.
levelRecord.dirty = function() { return false; };
response.success(levelRecord);
},
error: function(error) {
response.error("PlayerWorldLevelRank second count error: " + error.message);
}
});
},
error: function(error) {
response.error("PlayerWorldLevelRank first count error: " + error.message);
}
});
}
});
});
I don't think the issue is in your code. Like the error message states: the request times out. That is, the Parse API doesn't respond within the period of the timeout or the network causes it to timeout. As soon as you do .count some API call is probably done, which then can't connect or times out.
Apparently more people have this issue: https://www.parse.com/questions/ios-test-connectivity-to-parse-and-timeout-question. It doesn't seem possible to increase the timeout, so the suggestion in this post states:
For that reason, I suggest setting a NSTimer prior to executing the
query, and invalidating it when the query returns. If the NSTimer
fires before being invalidated, ask the user if they want to keep
waiting for the results to come back, or show them a message
indicating that the request is taking a long time to complete. This
gives the user the chance to wait more if they know their current
network conditions are not ideal.
In case you are dealing with networks, and especially on the mobile platform, you need to prepare for network hickups. So like the post suggests: offer the option to user to try again.

Categories

Resources