I'm using the Data module from Parse. I'm using HTML to create an email form. I use Javascript to get the form data (email), and then generate a username from the email address. This information is then saved to the Parse database.
Here's the HTML form code:
<form method="post" class="center">
<input id="email" name="email" type="email" placeholder="Type your email to create a Mail Link" />
<button id="submit" onclick="formSubmit();">Create</button>
</form>
Here's the Javascript:
function formSubmit() {
var emailValue = document.getElementById("email").value;
var userValue = emailValue.substr(0, emailValue.indexOf('#'));
Parse.initialize("---KEY---", "---KEY---");
var Users = Parse.Object.extend("Users");
var users = new Users();
users.save({username: userValue}).then(function(object) {
alert("Saved user");
});
users.save({email: emailValue}).then(function(object) {
alert("Saved email");
});
}
The problem is that the console is showing that the values are saved, however the data isn't saved into Parse.
Any ideas would be greatly appreciated!
In can make button a simple button, no need to change the button to a button as mention in the link you've mentioned, your code'll work fine.
You've written .then() method after saving the user data, but actually it's called to run the callbacks when the promise is fulfilled.
But here you're using simple Parse.Object, so either you've to use Parse.Promise, or if you want to use only simple Parse.Object when something like:-
users.save({
username: "Jake Cutter"
}, {
success: function(userObject) {
alert('The save was successful');
},
error: function(userObject, error) {
// The save failed. Error is an instance of Parse.Error.
// Do something if you want to do on error
}
});
For details you can check:-
https://www.parse.com/docs/js/symbols/Parse.Object.html#save
https://www.parse.com/docs/js/symbols/Parse.Promise.html#then
Okay, I awarded Indra the bounty, but here's the full answer for more context. This is an annoying problem, but you can solve it.
First, the form should use onsubmit.
<form method="post" onsubmit="formSubmit();">
Second, your function should use Indra's method to save data. But, you need event.preventDefault(); before it.
event.preventDefault();
userList.save({
username: "Peter Adams"
}, {
success: function(userList) {
alert('Success');
},
error: function(userList, error) {
alert('Failed to create new object, with error code: ' + error.message);
}
});
You can use jquery to store the form values and create a sub class of your parse class and also a new parse object to store the values in parse.
Example:
<form id="contact-form" >
First name:<br>
<input type="text" name="firstname" id="firstname">
<br>
Last name:<br>
<input type="text" name="lastname" id="lastname">
email:<br>
<input type="text" name="email" id="email">
<input type="submit" value="Get Access" />
</form>
Javascript code:
Parse.initialize("--KEY--", "--KEY--");
var Subscribers = Parse.Object.extend('Subscribers'); //create local parse object from your Parse class
$('#contact-form').submit(function(e) {
//on form submit
e.preventDefault();
//get data from form
var data = {
firstname: $("#firstname").val(),
lastname: $("#lastname").val(),
email: $("#email").val()
};
//create new Parse object
subscribers = new Subscribers();
//match the key values from the form, to your parse class, then save it
subscribers.save(data, {
//if successful
success: function(parseObj) {
alert(subscribers.get('firstname') + " " + subscribers.get('lastname') + " " + subscribers.get('email') + " saved to Parse.")
}
,
error: function(parseObj, error) {
console.log(parseObj);
console.log(error);
}
});
});
Related
Thank you all of you in advance! Really ><
There is a form inside a DIV to compose an email. Users enter recipient, title and content and click submit. The form can submit.
in html:
<form id='formid' name='compose1' action='/composemail' method='post'>
New Message
<p>To: <input type='textbox' name='recipient'></p>
<p>Subject: <input type='textbox' name='title'></p>
<p><input type='textarea' name='content' class='textarea'></p>
<input type='hidden' id='formTime' name='time' value='20:00:01 Wed Nov 06 2019'>
<input type='submit' id="formSubmit" value='Send'>
</form>
After clicking submit, the data is inserted into a mongo database. Data can be successfully added.
in app.js:
app.post('/composemail', express.urlencoded({extended:true}), function(req,res) {
var db = req.db;
var collection = db.get('emailList');
var sender = "abc#mail.com";
var recipient = req.body.recipient;
var title = req.body.title;
var time = req.body.time;
var content = req.body.content;
var mailbox = "Sent";
var newmail = {'sender':sender,'recipient':recipient,'title':title,'time':time,'content':content,'mailbox':mailbox};
collection.insert(newmail, function(err,result) {
if (err === null) {
console.log("Successfully added!");
res.json({success: true}); // <-problem here
} else res.send(err);
})
})
in another file call script.js, there is a function call show
function show() {
//basically a XMLHttpRequest to receive the email list from the database
}
The problem is the response after the data is inserted. I want it to stay at the same page and run show() function in script.js after the form is submitted.
I search on the internet and find this may be useful: res.json({success: true});
but I want to avoid using ajax as it is really complicated...
can I implement when success is true, then run show() function in the simple form in html? i have tried:
<form id='formid' name='compose1' action='/composemail' method='post' success='show(variable)'>
it seems not working... or if I really have to use ajax, how can i do it? i really have no idea about it...
Thank you very much!
I am trying to retrieve two strings from my Parse Customers class. I want to compare these strings (usernameAdmin, and passwordAdmin respectively) with the input field entered by the user, and if they matched it will take them to a specific page.
I am taking this approach for a particular reason, and would appreciate feedback.
$scope.logIn = function(form) {
var Customer = Parse.Object.extend("Customers");
parseAdminUsername = Customer.get('usernameAdmin');
parseAdminPassword = Customer.get('passwordAdmin');
if (form.lusername == parseAdminUsername && form.lpassword == parseAdminPassword) {
window.location = 'adminSelect.php'
} else {
alert('error');
}
};
The html code looks as follow:
<form role="form" ng-show="scenario == 'Sign up'">
<h4 id="wrongCredentials"></h4>
<input id="signupformItem" ng-model="user.lusername" type="email" name="email" placeholder="Email Address"> <br>
<input id="signupformItem" ng-model="user.lpassword" type="password" name="password" placeholder=" Password"> <br>
<br>
<button id="signupbuttonFinal" ng-click="logIn(user)" class="btn btn-danger"> Sign In</button>
</form>
I receive the following error on console:
undefined is not a function
at Object.$scope.logIn
below is the line
parseAdminUsername = Customer.get('usernameAdmin');
You are better off using Parse in built users instead of creating a separate object and then you would use Parse.User.logIn.
If you were to use your table instead. Customer.get('usernameAdmin') is used to return a field after you have performed a query to return records/s. You are best to perform a find query to check the username and password like so:
var Customer = Parse.Object.extend("Customers");
var query = new Parse.Query(Customer);
query.equalTo("usernameAdmin", form.lusername);
query.equalTo("passwordAdmin", form.lpassword);
query.find({
success: function(results) {
if (results.length > 0) {
window.location = 'adminSelect.php';
}
},
error: function(error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
I'd recommend not to use window and instead $window so that you can unit test your code. Better yet use angular routing and create a Single page app.
Using parse.com and javascript/jquery.
The below code should capture the input from the user in the "friendsearch" input box.
Once the submit button is clicked, it should query the parse.com backend and find out if the user exists. At the moment I keep getting "undefined" returned in "friendName" which I cannot spot why or what is causing the error?
<form class="Find Friend">
<div class="error" style="display:none"></div>
<input type="text" id="friendsearch" placeholder="Find Friend" class="input-field" required/>
<button type="submit" class="btn btn-login">Find</button>
</form>
var friendName;
$('#friendsearch').on('keyup', function(e) {
friendName = $(this).val();
});
var friendFinder = Parse.Object.extend("_User");
var query = new Parse.Query(Parse.User);
query.equalTo("username", friendName); // find users that match
query.find({
success: function(friend) {
alert(friendName);
},
error: function (error) {
//Show if no user was found to match
alert("Error: " + error.code + " " + error.message);
}
});
Ok, I revised your code so that the friendName variable actually contains the contents of the input box on your form. The problem was that your original code was trying to get access to the contents of your input box before it was even loaded into the DOM.
Try this for your HTML:
<form class="Find Friend">
<div class="error" style="display:none"></div>
<input type="text" id="friendsearch" placeholder="Find Friend" class="input-field" />
<button id="find_button" type="submit" class="btn btn-login">Find</button>
</form>
And this for your javascript:
var friendName;
function findFriend(){
friendName = $('#friendsearch').val();
alert(friendName);
var friendFinder = Parse.Object.extend("_User");
var query = new Parse.Query(Parse.User);
query.equalTo("username", friendName); // find users that match
query.find({
success: function(friend) {
alert(friendName);
},
error: function (error) {
//Show if no user was found to match
alert("Error: " + error.code + " " + error.message);
}
});
}
$('#find_button').click(function(e){
findFriend();
});
I updated the live jsFiddle example here: http://jsfiddle.net/LWA48/2/
In the jsFiddle example, the Parse object prints {"error": "Please use POST request"} when you click the button, but at least your friendName variable contains the name you typed in the box! Hopefully, this can take you the rest of the way.
I believe the problem is where you're assigning friendName = $(this).val();
Try using e.target to get a reference to the value currently in the text input box. I'm not sure if it's e.target off the top of my head but I'm fairly certain that you want a property contained inside the e argument.
Try $(e.target).val() or $(e.currentTarget).val() something like that instead of $(this).val();
What I also like to do when I'm trying to figure out why something isn't being set properly is to set a breakpoint in the chrome debugger. In this case, you can put 'debugger' in your code where you want the browser to break on. So in your example, you could write this:
$('#friendsearch').on('keyup', function(e) {
debugger
friendName = $(this).val();
});
And in your Chrome Dev Tools you can inspect the value of e and determine what properties and values are available.
I did a sample code using two templates.Those are :
Login Template - Login Form along with New User Button
Registration Template - Registration Form
Initially shows Login Template.So here when ever clicks a New User! Button in Login Template page then Immediately shows to Registration template page and hiding the Login Template page.In Reregistration Template Page Clicks Registration button if successfully registered then shows to Login Template Page and Hiding the Registration Template Page.I am new to Meteor. So Please see the below code & Suggest me how to do?
HTML Code :
<head>
<title>hcare</title>
</head>
<body>
{{> login}}
</body>
<template name="login">
<form id="login-form" action="action">
<div>
<h2> Login<h2>
<input type="text" id="username" placeholder="Enetr User Name" /><br>
<input type="password" id="pwd" placeholder="Password" /><br>
<input type="submit" value="Login" id="login" />
<input type="submit" value=" New User!" id="register" />
</div>
</form>
</template>
<template name="registration">
<form id="register-form" action="action">
<div>
<h2> Create Account<h2>
<input type="text" id="username" placeholder="Enter UserName" /><br>
<input type="text" id="name" placeholder=" Enter Name" /><br>
<input type="text" id="email1" placeholder=" Enter Email" /><br>
<input type="password" id="pwd1" placeholder=" Enter Password" /><br>
<input type="submit" value="Register" id="register" />
</div>
</form>
</template>
JS Code :
if (Meteor.isClient)
{
Template.login.events
({
'submit #login-form' : function (e,t)
{
// template data, if any, is available in 'this'
console.log("You pressed the button LOGIN ");
e.preventDefault();
// retrieve the input field values
var email = t.find('#email').value
, password = t.find('#pwd').value;
console.log(email);
Meteor.loginWithPassword(email, password, function (err)
{
if (err)
{
console.log(err);
Session.set("loginError", true);
}
else
{
console.log(" Login Success ");
}
});
}
});
Template.registration.events
({
'submit #register-form' : function (e,t)
{
console.log("You pressed the button Register ");
e.preventDefault();
var username = t.find('#username').value
, name = t.find('#name').value
, email = t.find('#email1').value
, password = t.find('#pwd1').value;
console.log("password="+password);
//var email = trimInput(email);
// var isValidPassword = function(val)
// {
// console.log("isValidPassword() "+val.length);
// return val.length >= 6 ? true : false;
// }
console.log("email="+email);
var isValidPassword = function(val, field)
{
if (val.length >= 6) {
return true;
} else {
Session.set('displayMessage', 'Error & Too short.')
return false;
}
}
if (isValidPassword(password))
{
console.log(" *** isValidPassword *** ");
Accounts.createUser({email: email, password : password,username : username }, function(err)
{
if (err)
{
console.log(err);
alert(err.reason);
}
else
{
console.log("Register Successfully");
}
});
}
}
});
}
if (Meteor.isServer)
{
Meteor.startup(function ()
{
// code to run on server at startup
});
}
I would start to add the Meteor Iron-Router package:
https://github.com/EventedMind/iron-router
read the docs and my be my tutorial, too (http://manuel-schoebel.com/blog/iron-router-tutorial).
Then you can easily set up two different routes, one for login and one for register with the Iron-Router.
You can then simply create normal links to switch from /login to /register.
The Iron-Router makes it really much easier, so I would highly suggest to take some time and really understand how it works (it is not that hard).
Good choice to learn Meteor, by the way :-)
To answer your question in your comment:
First of all, you should use the Iron-Router on windows, too. But without it you could render a template depending on the Session.
<body>
{{> content}}
</body>
<template name="content">
{{renderTemplate}}
</template>
Content Helper
Template.content.helpers({
'renderTemplate': function(){
return new Handlebars.SafeString(Template[Session.get('currentTemplate')]({dataKey: 'someValue'})
}
})
Now in the content template should be the template rendered that is in your Session.get('currentTemplate').
You can then simply change the Session variable if someone clicks:
Template.login.events({
'click #register': function(evt, tpl){ Session.set('currentTemplate', 'registration');}
})
Because the Session is a reactive data source and it knows, that the renderTemplate helper method depends on this specific data, it will re run the renderTemplate function. And now the registration template will be rendered.
Also make sure that you set the currentTemplate variable in your clients startup function to 'login'. (Session.set('currentTemplate', 'login'))
Otherwise nothing will show up at first and an error would occur.
This is not tested code, but it should give you a direction... And might even work ;-P
Edit:
You also do not want your input #register button to have the type="submit", make it type="button" so that the form will not be submitted! You can also add to your 'click #register' event-handler this:
evt.preventDefault()
Just to make sure the form will not be submitted.
I was trying to add a second form to a javascript/jquery script that I wrote, however, when i implemented and began testing it, when I would try to send the firm form via a jquery post request, it would instead send a get request. I know that this has to do with the second form, because commenting the script out for the second form makes the site work again. Hopefully a pair of fresh eyes can help!(the loadpage function works as well)
The register function seems to be where the problem is:
//when the user first goes to the page
$(document).ready(function(){
var user = $("#username");
var pass = $("#password");
var submit = $("#submit");
//both of these methods work, I'm not sure if one is better than the other
//$("#submitbutton").click(function(event){
$("#loginform").on('submit', function(event){
event.preventDefault();
$('.loginerror').remove();
$.post("login.php", {username:user.val(), password:pass.val()}, function(data){
if(!data)
{
$("#login").append("<h3 class='loginerror'>Incorrect Username or Password</h3>");
}
else
{
loadpage();
}
}, "json");
});
//if the user clicks the username prompt him with the login div
$("#registerbutton").click(function(event){
register();
});
});
function register()
{
$("#login").hide("slow");
$("#registerdiv").css("display", "block");
//initiate some variables
var regusername = $("#regusername");
var reg1password = $("#reg1password");
var reg2password = $("#reg2password");
var regemail = $("#regemail");
var regfirstname = $("#regfirstname");
var reglastname = $("#reglastname");
//TODO: check to make sure form is filled out properly
$("#registerform").on('submit', function(event){
event.preventDefault();
//send post request
$.post("register.php", {regusername:regusername.val(), password1:reg1password.val(), password2:reg2password.val(), email:regemail.val(), firstname:regfirstname.val(), lastname:reglastname.val()}, function(data){
if(!data)
$("#registerdiv").append("<h3> class='loginerror'>Server error, retry</h3>");
else
$("#registerdiv").hide("slow");
$("#loginiv").slidedown("slow");
}, "json");
}
And here's the HTML with the two forms:
<body>
<Div id="welcome"> Welcome </div>
<Div id="login">
<br><br><h2>Welcome to QuotesLib</h2>
<br><br><br><form id="loginform"> Username:
<input type = "text" name = "username" id ="username"> <br> Password:
<input type = "password" name = "password" id = "password"> <br>
<input type = "submit" name="submitbutton" id="submitbutton" class = "bluebutton">
</form>
<form><br><br><br>Don't have an account yet?<br><button id="registerbutton" name="registerbutton" href="register.html">Register Now</button>
</Div>
<Div id="registerdiv">
<br><br><h2>Sign Up For QuotesLib</h2>
<br><form id="registerform"> Username:
<input type ="text" id="regusername"> <br> Password:
<input type ="password" id="reg1password"> <br> Repeat Password:
<input type ="password" id="reg2password"> <br> First Name:
<input type ="text" id="regfirstname"> <br> Last Name:
<input type ="text" id="reglastname"> <br> email:
<input type ="text" id="regEmail"> <br>
<input type ="submit" id ="registersubmitbutton">
<br> </form>
</Div>
It would be super helpful if someone could give me an answer to this question!
$("#registerdiv").append("<h3> class='loginerror'>Server error, retry</h3>");
should be
$("#registerdiv").append("<h3 class='loginerror'>Server error, retry</h3>");
see the difference:
<h3>... and <h3 ...
The code has some mistakes,
first,
<form><br><br><br>Don't have an account yet?<br><button id="registerbutton" name="registerbutton" href="register.html">Register Now</button>
You are having a form open tag but not a close tag, the form tag even not needed for this button, and that was the main reason for the problem
second, the end of the JS code,
}, "json");
}
should be
}, "json");
});
}
I'm not sure whether you missed while copying,
Third,
The <h3> tag within the append method, though it is not the matter for the problem you are having.
It is better to use some text editors which hi-lights the code open, end tags, braces.
Here the working code