Sending form data to Parse.com - javascript

I have a form that I created and I want to send that form information to a backend database called Parse.com. I create the table in Parse with the same names as the fields on the form, but I'm not sure how to send it to Parse using js.
<form id="contact-form" class="contact-form" method="post" action="" onSubmit="return checkMail()" name="validation">
<div class="form-group row" id="price">
<div class="col-lg-4">
<input type="text" name="fname" class="form-control" id="name" placeholder="First *" required >
</div>
<div class="col-lg-4">
<input type="text" name="lname" class="form-control" id="name" placeholder="Last *" required>
</div>
<div class="col-lg-4">
<input type="text" name="email" class="form-control" id="name" placeholder="E-mail *" required>
</div>
</div>
</div>
<div class="form-group row" align="center">
<div class="col-lg-12" align="center">
<button type="submit" class="button default">SEND <i class="glyphicon glyphicon-send"></i></button>
</div>
</div>

Attach your parse object save function to the form submit. This can be achieved with ease by using JQuery.
Next you have to capture the form input data, then save it to your Parse object.
This script assumes you have created a class in parse with the [string] columns of fname, lname and email.
<script>
Parse.initialize("API KEY", "JAVASCRIPT KEY");
var ParseObj = Parse.Object.extend('myClass'); //create local parse object from your Parse class
$('#contact-form').submit(function(e) {
//on form submit
e.preventDefault();
//get data from form
var data = {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val()
};
//create new Parse object
parseObj = new ParseObj();
//match the key values from the form, to your parse class, then save it
parseObj.save(data, {
//if successful
success: function(parseObj) {
alert(parseObj.get('fname') + " " + parseObj.get('lname') + " " + parseObj.get('email') + " saved to Parse.")
}
,
error: function(parseObj, error) {
console.log(parseObj);
console.log(error);
}
}
);
});
</script>

This is a typical "too broad" question, as you're not really having a specific problem but just asking us to write the code for you. Best I can do is point you to the parse.com user guide which shows you how you can do this. Check it out, try it for yourself and then ask here again if you have specific issues with the code.
Example snipped from the user guide found here: https://parse.com/docs/js_guide#objects-saving
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);
}
});

Related

Unable to use variable containing string in place of hardcoded string

I am setting up Stripe on my web app. Stripe seems to work fine when I hardcode a string such as 'test#test.com' into the email parameter. When I try to use the value from the input box however, the code does not execute properly. I do not get an error, the code just simply does not execute further. Here is my code:
form.addEventListener('submit', function (event) {
var user_email = document.getElementById('example1-email').value;
document.getElementById('output').innerHTML = user_email;
event.preventDefault();
stripe.createPaymentMethod({
type: 'card',
card: cardElement,
billing_details: {
email: user_email
},
}).then(stripePaymentMethodHandler);
});
function stripePaymentMethodHandler(result, email) {
if (result.error) {
} else {
// Otherwise send paymentMethod.id to your server
fetch('/checkout_stripe', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: user_email,
payment_method: result.paymentMethod.id
}),
}).then(function (result) {
return result.json();
}).then(function (customer) {
// The customer has been created
}).then(redirectfunc);
}
HTML:
<form id="subscription-form">
<div class="cell example example1" id="example-1" style="padding-left: 25%;padding-right: 25%;padding-top: 5%">
<br>
<fieldset>
<div class="row">
<label for="example1-name" data-tid="elements_examples.form.name_label">Name</label>
<input id="example1-name" data-tid="elements_examples.form.name_placeholder" type="text" placeholder="Jane Doe" required
autocomplete="name">
</div>
<div class="row">
<label for="example1-email" data-tid="elements_examples.form.email_label">Email</label>
<input id="example1-email" data-tid="elements_examples.form.email_placeholder" type="email" placeholder="janedoe#gmail.com"
required autocomplete="email">
</div>
<div class="row">
<label for="example1-phone" data-tid="elements_examples.form.phone_label">Phone</label>
<input id="example1-phone" data-tid="elements_examples.form.phone_placeholder" type="tel" placeholder="(941) 555-0123" required
autocomplete="tel">
</div>
</fieldset>
<fieldset>
<div class="row">
<div id="example1-card"></div>
</div>
<form id="subscription-form">
<div id="card-element" class="MyCardElement">
<!-- Elements will create input elements here -->
</div>
<!-- We'll put the error messages in this element -->
<div id="card-errors" role="alert"></div>
</fieldset>
<button type="submit" style="background-color: #27eb15">Subscribe</button>
</form>
This is just the stock code from Stripe, with me pulling in the string from the input box and trying to put it into the email param. Bizarrely, only a hardcoded string such as test#test.com allows the process to complete, but not just using the var user_email - despite that just being a string that contains the same string as the hardcoded.
I have tested whether or not I am actually pulling anything in when I use the .value, and I am. I have also tested the datatype of user_email, and it is indeed a string.
How can I get this to execute properly using the data pulled in from the user input boxes?

How can I send an array of values from the inputs to the controller

I've got a number of inputs in a form, created dynamically, and I'm trying to send them to the controller as an array using javascript.
Originally it was only one value and it was part of the Entity I pass in the model. Then, as it can be more than one, I added a Transient field to the entity as a List and also created another class in java with just a List. However, I still don't know how to add these values from javascript to the th:object in the form.
<form id="selectform" th:object="${systemIdListForm}" th:action="#{/myController}" method="get">
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
<script type="text/javascript">
/*<![CDATA[*/
$(document).ready(function () {
$("#addMore").click(function() {
var html = '<div class="form-group col-md-1"><input class="form-control" name="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/></div>';
$('#fields').append(html);
});
$("#selectform").submit(function(){
var values = $(this).serialize();
});
});
/*]]>*/
</script>
At the moment I can see that the variable values have the right information but nothing is sent to the controller. I realize that the formatting of these values is probably not want I need but I'm not sure what to do.
Any help is much appreciated
What data type have you used in Model ?
Make sure you have taken String [] for that field.
If not taken String [] then use that and let me know whether it works or not.
Also you can take help of below code.It is for your case only.
$("#selectform").submit(function (event) {
// form redirect stop
event.preventDefault();
var status = jbf.form.validate('#selectform');
if (!status) {
return;
}
// get form data
var data = {};
data["enrollmentNumber"] = $("#enrollmentNumber").val();
data["systemIdInput"] = jQuery("#selectform input[name=systemIdInput]").val();
var url = "/yourURL";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response) {
var message = response.message;
//success notification
if(response.success === true){
alert(message);
}else{
error(message);
}
},
error: function (e) {
console.log("ERROR: ", e);
error("Add failed");
}
});
});
I managed to get the list of values from all the inputs in the form using a hidden input. I added a transient field in my entity (systemIds) where I've got all the values.
<form id="selectform" th:object="${myEntiry}" th:action="#{/crops/singlecroplabeloffinsp/list/1}" method="get">
<input class="form-control" id="systemIdList" th:field="*{systemIds}" type="hidden"/>
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
...
$("#selectform").submit(function(){
//get all the system ids
var x = document.getElementsByName("systemIdInput");
var systemIds = [];
for (i = 0; i < x.length; i++ ) {
if (x[i].type ='text') {
systemIds.push(x[i].value);
}
}
$("#systemIdList").val(systemIds);
this.submit();
});
Added to the entity with getter & setter:
#Transient
private List<Integer> systemIds;

How to submit form and have data stay in input field? Using AJAX and nodejs

I am trying to create a user settings page where a user inputs his/her information, clicks "save", then the page saves the data without clearing the inputted fields or reloading the page. The best example I can think of is the user account settings page on Udemy.
A LOT of the similar questions I've looked at are using php or renders data in a div below the form. I want the data to remain IN the form inputs. I'm using nodejs, express, bodyparser.
<form id="updateAccSettings" action="/account" method="POST">
<div class="form-group">
<label for="address">Address* </label>
<input class="form-control" type="text" name="address" placeholder="Address" required/>
</div>
<div class="form-group">
<label for="address2">Address 2 </label>
<input class="form-control" type="text" name="address2" placeholder=""/>
</div>
<div class="form-group">
<label for="city">City* </label>
<input class="form-control" type="text" name="city" placeholder="City" />
</div>
<div class="form-group">
<input type="submit" name="save" class="btn btn-lg btn-primary btn-block" value="Save"/>
</div>
</form>
I've tried this with AJAX
$(document).ready(function() {
$("#updateAccSettings").on("submit", function(e){
e.preventDefault();
var details = $("#updateAccSettings").serialize();
$.post("/account", details, function(data){
$("#updateAccSettings").html(data);
});
});
});
and this
$(document).ready(function () {
$("#updateAccSettings").bind("submit", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/account",
data: $("#updateAccSettings").serialize(),
success: function(){
alert("You've successfully updated your account settings.")
}
});
});
});
And I have this for my app.js
app.post("/account", function(req, res) {
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = {address: address, address2: address2, city: city};
account.push(updateAccount);
console.log("Updated data");
res.redirect("/settings/account");
});
When I clicked save, I get a Cannot read property of 'push' undefined. I tried deleting the var address, var address2, etc and keeping only the console.log which logs whenever I click save but doesn't keep the data in the input. I tried adding onsubmit="return false" as an attribute on the form tag but the console.log doesn't run when I click save so I assume it's not doing anything with the data.
Not sure how to proceed from here. All my other forms use modals or render results in another page.
You're getting the error because you're trying to push onto an undefined variable. Namely in the last section when posted this app.post:
app.post("/account", function(req, res) {
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = {address: address, address2: address2, city: city};
account.push(updateAccount); // error is being thrown here
console.log("Updated data");
res.redirect("/settings/account");
});
Once you have a dummy variable for account, you can send back to the frontend a json response to be read in the form success handler.
Example code: (I haven't tested it)
Backend:
app.post("/account", function(req, res) {
var account = [];
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = { address, address2, city };
account.push(updateAccount); // error is being thrown here
console.log("Updated data");
res.json(updateAccount);
});
Frontend:
$(document).ready(function () {
$("#updateAccSettings").bind("submit", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/account",
data: $("#updateAccSettings").serialize(),
success: function(data){
$('#address').value(data.address);
$('#address2').value(data.address2);
$('#city').value(data.city);
}
});
});
});
You could give each of your form input fields an id (e.g the same as their "name" property)and get their values individually when doing the ajax request as follows (that way you can reinsert the values after the form is submitted):
HTML
<form id="updateAccSettings" action="" method="POST">
<div class="form-group">
<label for="address">Address* </label>
<input class="form-control" type="text" name="address" id="address" placeholder="Address" required/>
</div>
<div class="form-group">
<label for="address2">Address 2 </label>
<input class="form-control" type="text" name="address2" id="address2" placeholder=""/>
</div>
<div class="form-group">
<label for="city">City* </label>
<input class="form-control" type="text" name="city" id="city" placeholder="City" />
</div>
<div class="form-group">
<input type="submit" name="save" class="btn btn-lg btn-primary btn-block" value="Save"/>
</div>
</form>
JQuery
$(document).ready(function() {
$("#updateAccSettings").on("submit", function(e){
e.preventDefault();
//get the values of our input fields and store them in local variables
var address = $("#address").val();
var address2 = $("#address2").val();
var city = $("#city").val();
//prepare the data object to send in the ajax request
var params = {"address": address, "address2": address2, "city" : city};
$.ajax({
type: "POST",
url: "/account",
data: JSON.stringify(params),
dataType: "json",
success: function(data){
//the ajax request was successful
//We can do something with the data we get back here.
//Also we can reinsert the values (that were submitted) to the form
$("#address").val(address);
$("#address2").val(address2);
$("#city").val(city);
},
error: function(xhr, status, error) {
//an error occured in the request so handle it here
}
});
});
});

Validate form, check if user exists, register them. All with Ajax

My javascript is inside an html file called register.html.
The user submits the form. This should then trigger the $('input[name="createacc"]').click(function (e) AJAX then sends those 4 variables to checkuser.php. Checkuser.php should then check to see if the username exists. If it does exist, it should echo 0. If it does not exists, it should echo 1. Register.html then checks to see what checkuser.php echoed. If the echo was "0" then, then an alert box should appear saying username unavailable. If the echo was "1" or anything else, register.html should run $("#registerform").submit(); which then does the php script. This should all happen without leaving the register.html page.
I check chrome's built in debugger and I see that if the account exists checkuser.php writes back 0 and if the account doesn't it writes back 1. But for some reason nothing else happens. The account does not register nor do I get an alert box saying the username is unavailable
here is my register.html
<form ata-parsley-validate name="registerform" id="registerform" action="register.php" method="post">
<p>
<label for="firstname">First Name:</label>
<input name="firstname" id="firstname" maxlength="32" type="text" placeholder="Optional" />
</p>
<p>
<label for="username" id="usernameText">Username:</label>
<input data-parsley-pattern="^[A-Za-z0-9_]{3,15}$" data-parsley-length="[3, 15]" name="username" id="username" maxlength="32" type="text" data-parsley-error-message="Username needs to be between 3 and 15 characters. Case sensitive. No special characters allowed." required/>
</p>
<p>
<label for="password1">Password:</label>
<input name="password1" id="password1" data-parsley-pattern="^[A-Za-z0-9_-]{5,25}$" data-parsley-length="[5, 25]" type="password" data-parsley-equalto="#password2" data-parsley-error-message="Passwords must match. Needs to be between 5 and 25 characters. Case sensitive. No special characters allowed." required/>
</p>
<p>
<label for="password2">Confirm Your Password:</label>
<input name="password2" id="password2" data-parsley-length="[5, 25]" data-parsley-error-message="Passwords must match. Needs to be between 5 and 25 characters. Case sensitive. No special characters allowed." data-parsley-pattern="^[A-Za-z0-9_-]{5,25}$" type="password" data-parsley-equalto="#password1" required/>
</p>
<p>
<label for="email">E-Mail:</label>
<input data-parsley-trigger="change" name="email" id="email" maxlength="1024" type="email" required/>
</p>
<p>
<input type="submit" id="submit" class="submit" name="createacc" value="Register" />
</p>
</form>
Here is my javascript
<script>
$(document).ready(function () {
$('input[name="createacc"]').click(function (e) {
var username = $('input[name="username"]').val();
var firstname = $('input[name="firstname"]').val();
var password1 = $('input[name="password1"]').val();
var email = $('input[name="email"]').val();
e.preventDefault();
$.ajax({
type: 'POST',
data: {
username: username,
firstname: firstname,
password1: password1,
email: email
},
url: 'checkuser.php',
success: function (data) { //Receives the data from the php code
if (data === "0") {
alert("Username Unavailable");
} else {
$("#registerform").submit();
alert("Account successfuly created");
}
},
error: function (xhr, err) {
console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
console.log("responseText: " + xhr.responseText);
}
});
});
});
</script>
Update - I have fixed parts of my code through the help of others below me. My only issue now is that $("#registerform").submit(); doesn't do anything
You are trying to return and JSON not setting
header('Content-type: application/json');
Decide whether you want to pass plaintext or json. Your string might be now "0", not 0
Try
if (data === '"0"') {
I think the problem is in your success.you have written If it does exist, it should echo 0. If it does not exists, it should echo 1.you should use:
success: function (data) { //Receives the data from the php code
if (data == '"0"') { //register if user exists.
$("#registerform").submit();
} else {
alert("Username Unavailable");
}

Parse.com javascript login

Hi Stackoverflow members,
I started learning javascript a couple days ago but was stumped on one of the problems i came across.
Form:
<form class="login-form" method="post" onsubmit="return tryLogin(this);">
<h3 class="form-title">Login to your account</h3>
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span>
Enter any username and password.
</span>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">Username</label>
<div class="input-icon">
<i class="fa fa-user"></i>
<input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username" id="username"/>
</div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<div class="input-icon">
<i class="fa fa-lock"></i>
<input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password" id="password"/>
</div>
</div>
<div class="form-actions">
<label class="checkbox">
<input type="checkbox" name="remember" value="1"/> Remember me </label>
<button type="submit" class="btn green pull-right">
Login <i class="m-icon-swapright m-icon-white"></i>
</button>
</div>
</form>
Javascript:
<script type="text/javascript">
jQuery(document).ready(function() {
App.init();
Login.init();
});
function tryLogin(form) {
var username = form.username.value;
var password = form.password.value;
console.log("Username: " + username + " Password: " + password);
Parse.User.logIn(username, password, {
success: function(user) {
window.location.href="dashboard.html";
//self.undelegateEvents();
//delete self;
alert("Sucess");
return true;
},
error: function(user, error) {
window.location.href="login.html";
alert("Error: " + error.code + " " + error.message + username + password);
return false;
}
});
}
</script>
The problem is that when I attempt to login I get a 100 XMLHttpRequest failed error. This only happens when I input data into the form and click log in. If i don't enter any data and click login, it correctly attempts to login. If i put the username + password directly into the javascript it also works - but doesn't through the form.
Console.log, logs the correct username and password being inputted, but the Parse.User.logIn(username, password) doesn't want to pass it in... but it works if I fill it in like this:
Parse.User.logIn("myemail#email.com", "mypassword", {....
Any help would be appreciated.
Cheers!
Edit: Here's the error
XMLHttpRequest failed: {"statusText":"","status":0,"response":"","responseType":"","responseXML":null,"responseText":"","upload":{"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null},"withCredentials":false,"readyState":4,"timeout":0,"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null}
Could it be a MAMP issue? PS: Creating new objects etc. works fine.
As you dont call preventDefault on the submit event, what happens is that it posts form when you click which has for effect to cancel the ajax call Parse.User is making.
Add event.preventDefault(); in your event handler and you should be fine.
<form class="login-form" method="post" onsubmit="tryLogin(this); event.preventDefault();">
Or better use jQuery to manage this event
$(".login-form").submit (function(event) {
...
event.preventDefault();
});

Categories

Resources