So basically i am trying to implement 2checkout in my website and i have done everything from documentation but i get this error: TwoCheckoutException: Bad request - parameter error. I tried checking and playing with private/public keys and id but when i change them it says "authoization error" so i am sure they are okay. I read about addresses and everything and i have changed them but still not working.
Here is my full code:
#{
ViewData["Title"] = "Test";
}
<script type="text/javascript" src="https://www.2checkout.com/checkout/api/2co.min.js"></script>
<h2>Test</h2>
<form id="myCCForm" action="/Home/SubmitCard" method="post">
<input name="token" type="hidden" value="" />
<div>
<label>
<span>Card Number</span>
<input id="ccNo" type="text" value="" autocomplete="off" required />
</label>
</div>
<div>
<label>
<span>Expiration Date (MM/YYYY)</span>
<input id="expMonth" type="text" size="2" required />
</label>
<span> / </span>
<input id="expYear" type="text" size="4" required />
</div>
<div>
<label>
<span>CVC</span>
<input id="cvv" type="text" value="" autocomplete="off" required />
</label>
</div>
<input type="submit" value="Submit Payment" />
</form>
<script type="text/javascript">
// Called when token created successfully.
var successCallback = function (data) {
var myForm = document.getElementById('myCCForm');
// Set the token as the value for the token input
myForm.token.value = data.response.token.token;
// IMPORTANT: Here we call `submit()` on the form element directly instead of using jQuery to prevent and infinite token request loop.
myForm.submit();
};
// Called when token creation fails.
var errorCallback = function (data) {
if (data.errorCode === 200) {
alert("Error 200");
// This error code indicates that the ajax call failed. We recommend that you retry the token request.
} else {
alert(data.errorMsg);
}
};
var tokenRequest = function () {
// Setup token request arguments
var args = {
sellerId: "901417674",
publishableKey: "309FC596-8380-4B6F-B269-3E157A5A5D0B",
ccNo: $("#ccNo").val(),
cvv: $("#cvv").val(),
expMonth: $("#expMonth").val(),
expYear: $("#expYear").val()
};
// Make the token request
TCO.requestToken(successCallback, errorCallback, args);
};
$(function () {
// Pull in the public encryption key for our environment
TCO.loadPubKey('sandbox');
$("#myCCForm").submit(function (e) {
// Call our token request function
tokenRequest();
// Prevent form from submitting
return false;
});
});
</script>
and here is server side code:
public IActionResult SubmitCard()
{
TwoCheckout.TwoCheckoutConfig.SellerID = "901417674";
TwoCheckout.TwoCheckoutConfig.PrivateKey = "4E704021-B233-435F-A904-47B2620B9E66";
TwoCheckout.TwoCheckoutConfig.Sandbox = true;
try
{
TwoCheckout.AuthBillingAddress Billing = new TwoCheckout.AuthBillingAddress();
Billing.addrLine1 = "123 Main Street";
Billing.city = "Townsville";
Billing.zipCode = "43206";
Billing.state = "Ohio ";
Billing.country = "USA";
Billing.name = "Joe Flagster";
Billing.email = "Ex#a.com";
Billing.phoneNumber = "065";
TwoCheckout.ChargeAuthorizeServiceOptions Customer = new TwoCheckout.ChargeAuthorizeServiceOptions();
Customer.total = 1;
Customer.currency = "USD";
Customer.merchantOrderId = "12";
Customer.billingAddr = Billing;
Customer.token = Request.Form["token"];
TwoCheckout.ChargeService Charge = new TwoCheckout.ChargeService();
var result = Charge.Authorize(Customer);
return View("Success", result);
}
catch(TwoCheckout.TwoCheckoutException ex)
{
return View("Error", ex.ToString());
}
}
and here is all info from my sandbox:
You may need to update your site settings for sandbox from Site Management -> Site Settings and Turn to On for Demo Settings and check again
May it helps you
Related
I am not a javascript coder, but was trying to figure out a solution with using HTML Web Forms and Javascript... However, I am using a while loop to keep checking the status of a submitted job, but because I am doing this, the page freezes. Is there way to check the status without having the page freeze?
<!DOCTYPE html>
<html>
<body>
<p><span style="background-color:{color}; border-radius:3px; color:#ffffff; float:right; font-size:16px; padding:2px 4px 2px 4px"><a id='downLoad' href="" download='file' style='display:none' target='_blank'>Save file As</a></span><span style="font-size:24px"><span style="color:#d52b40">Print Survey Report </span></span></p>
<p>Enter the project <b>Print ID</b> and <b>File Name</b> then submit the report for print. Repot may take a few minutes, but a <b>Save File As link</b> will show when ready for download. Right click and select <b>Save Link As</b></p>
<form id='printSurvey'>
<input type="hidden" id="portalUrl" name="portalUrl" value="https://transportation.bd.esri.com/portal">
<input type="hidden" id="templateItemId" name="templateItemId" value="a19dc0354ade4e9da65086453d89aa4a">
<input type="hidden" id="surveyItemId" name="surveyItemId" value="901946f3a7f940f4bab7bbda9d7595e3">
<input type="hidden" id="featureLayerUrl" name="featureLayerUrl" value="https://transportation-rh.bd.esri.com/server/rest/services/Geotech/GeotechProjectInfoPointSDE/FeatureServer/2">
<input type="hidden" id="token" name="token" value="toekn was removed">
<input type="hidden" id="outputFormat" name="outputFormat" value="docx">
<input type="hidden" id="uploadInfo" name="uploadInfo[type]" value="arcgis">
<input type="hidden" id="uploadInfo" name="uploadInfo[parameters][folderId]" value="6128cd36706f40ddaaa387e9296032a9">
<input type="hidden" id="uploadInfo" name="uploadInfo[parameters][conflictBehavior]" value="rename">
<label for="queryParameters">Print ID:</label>
<input type="text" id="queryParameters" name="queryParameters[objectIds]" placeholder="i.e 1"><br><br>
<label for="outputReportName">Report Name:</label>
<input type="text" id="outputReportName" name="outputReportName" placeholder="Logging Report Name"><br><br>
<input type="hidden" id="outputPackageName" name="outputPackageName" >
<input type="submit" type="buton" value="Submit">
</form>
<script>
document.getElementById("outputReportName").addEventListener('focusout',function () {
document.getElementById("outputPackageName").value = this.value;
});
const downLoadTag = document.getElementById('downLoad');
function httpGet(url){
let xmlHttpReq = new XMLHttpRequest();
var url = url +'?portalUrl=https://transportation.bd.esri.com/portal&token=token was removedenter code here'
xmlHttpReq.open("GET", url, false);
xmlHttpReq.send(null);
return JSON.parse(xmlHttpReq.responseText);
}
window.addEventListener("load", () => {
function sendData() {
const XHR = new XMLHttpRequest();
// Bind the FormData object and the form element
const FD = new FormData(form);
// Define what happens on successful data submission
setTimeout(XHR.addEventListener("load", (event) => {
//alert(event.target.responseText['jobId']);
var responseArray = JSON.parse(event.target.responseText);
var jobID = responseArray['jobId'];
var urlPath = 'https://survey123.arcgis.com/api/featureReport/jobs/'+jobID
var status = 'esriJobExecuting'
alert('Report is being generated... This may take several minutes');
var countEnd = 0
while (status != 'esriJobSucceeded') {
var getRep = httpGet(urlPath)
if (getRep['jobStatus'] == 'esriJobSucceeded'){
var itemID = getRep['resultInfo']['resultFiles'][0]['id'];
var urlBeg = 'https://transportation.bd.esri.com/portal/sharing/rest/content/items/';
var urlEnd = '/data?token=token was removed';
downLoadTag.href = urlBeg +itemID+urlEnd;
//console.log(getRep['resultInfo']);
status = getRep['jobStatus'];
//console.log(getRep);
alert('Report is ready for download')
};
};
downLoadTag.style='display:show';
}), 5);
// Define what happens in case of error
XHR.addEventListener("error", (event) => {
alert('Oops! Something went wrong.');
});
// Set up our request
XHR.open("POST", 'https://survey123.arcgis.com/api/featureReport/createReport/submitJob');
// The data sent is what the user provided in the form
XHR.send(FD);
};
// Get the form element
const form = document.getElementById("printSurvey");
// Add 'submit' event handler
form.addEventListener("submit", (event) => {
event.preventDefault();
sendData();
});
});
</script>
</body>
</html>
I struggled with the same problem recently. There is a Web Workers API. It does everything in the background and doesn't block the main thread. It is easy to learn and understand. Just google Web Workers API and you will get it!
I have a page that contains some required fields. An attachment file field, some text boxes including checking email valid and matching and making sure not empty, and selecting a checkbox to ensure user acknowledges terms and conditions.
The problem I have is, if I don't fill out the form and click 'Buy now', it does perform a validation, but it then redirects the user to checkout. How can we get it so that the submit button does not redirect, if there are validation present on the form? I use required in html and some javascript for email validation.
HTML FROM
<form id="tcform">
<p>
<b>Attach your CV:</b> (.doc, .docx, .pdf, .txt, .rtf)
</p>
<input type="file" id="uploadCV" required/>
<br/><br/>
<div class="formcontainer">
<label for="email"><b>Email:</b></label>
<input type="input" id="email" name="email" />
<p id="resultEmail"></p>
<label for="email"><b>Confirm Email:</b></label>
<input type="input" id="confirmEmail" name="confirmEmail" />
<p id="resultConfirmEmail"></p>
<label for="job"><b>Desired Job Position:</b></label>
<input type="input" id="job" name="job" required />
</div>
<br/>
<p><b>Quantity:</b> 1</p>
<b class="price">Price:</b> £40
<button type="submit" class="btn btn-default buynow"
id="checkout-button-sku_xxx" role="link">
Buy Now
</button>
<p class="tcparagraph"><i style="font-size:small">Expected Completion Time: Within 10 working days</i></p>
<p class="tcparagraph"><input id="field_terms" type="checkbox" required name="terms"> I accept the <u>Terms and Conditions</u></p>
</form>
Javascript
<script>
var file = document.getElementById('uploadCV');
file.onchange = function(e) {
var ext = this.value.match(/\.([^\.]+)$/)[1];
switch (ext) {
case 'doc':
case 'docx':
case 'pdf':
case 'txt':
case 'rtf':
break;
default:
alert('Please upload a file that matches any of these file types: .doc, .docx, .pdf, .txt, .rtf');
this.value = '';
}
};
(function() {
var stripe = Stripe('pk_test_xxxxxxxxxxxxxx');
var checkoutButton = document.getElementById('checkout-button-sku_xxx');
checkoutButton.addEventListener('click', function () {
// When the customer clicks on the button, redirect
// them to Checkout.
stripe.redirectToCheckout({
items: [{sku: 'sku_xxx', quantity: 1}],
// Do not rely on the redirect to the successUrl for fulfilling
// purchases, customers may not always reach the success_url after
// a successful payment.
// Instead use one of the strategies described in
// https://stripe.com/docs/payments/checkout/fulfillment
successUrl: window.location.protocol + '//www.xxx.com/services/cv-rewrite',
cancelUrl: window.location.protocol + '//www.xxx.com/services/cv-rewrite',
})
.then(function (result) {
if (result.error) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer.
var displayError = document.getElementById('error-message');
displayError.textContent = result.error.message;
}
});
});
})();
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate() {
var $result = $("#resultEmail");
var $confirmResult = $("#resultConfirmEmail");
var email = $("#email").val();
var confirmEmail = $("#confirmEmail").val();
$result.text("");
if (validateEmail(email)) {
if (email == confirmEmail) {
$confirmResult.text("");
return true;
} else {
$confirmResult.text("Your email and confirm email do not match");
$confirmResult.css("color", "red");
}
} else {
$result.text("You have not provided a valid email");
$result.css("color", "red");
}
return false;
}
$(".buynow").on("click", validate);
window.onload = function(){
var label = document.getElementsByClassName('close');
for (var i = 0; i<label.length; i++) {
label[i].onclick = function () {
var el = (this.parentNode);
el.parentNode.removeChild(el);
};
}
};
</script>
You should call your validate method before the stripe redirect and you should also check the forms default validation (form.checkValidity()) for things that you do not manually check in your validate method.
checkoutButton.addEventListener('click', function(event) {
event.preventDefault();
// When the customer clicks on the button, redirect
// them to Checkout if validations pass.
const isFormValid = checkoutButton.form.checkValidity() && validate();
if (!isFormValid) return; // or show message or whatever else you want
stripe.redirectToCheckout({
items: [{
sku: 'sku_xxx',
quantity: 1
}],
...
I am currently working on an website project that my friends and I would like to publish in the future. I´m currently building the html and css side of the page and need to implement dynamic events (if that's how its called) in the page for customer input.
I have a very little understanding when it comes to javascript/jquery (I am able to get a general idea of what is happening, yet my syntax comprehension is poop) and have only a basic knowledge of html and css. Now, I am aware that my inquiry is extensive and I would really appreciate any help, or pointers in the right direction!
So far the different blocks of code that I have found and tried by googling have worked for me, but only in executing individual functions (e.g.: the toggle function works but the create.element function doesn't).
This is my current html code that I am trying to modify with Javascript:
<div class="bttiendas">
<button class="btndag">Agregar</button>
<button class="btndgu">Guardar</button>
</div>
<div class="rdatos">
<form class="thf">
<input class="morehf" type="button" value="+/-" />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="edithf" type="button" value="Edit" />
<input class="erasehf" type="reset" value="Erase" />
</form>
<form class="trf">
<input class="crf" type="text" placeholder="POS" readonly />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
</form>
</div>
What I am trying to accomplish with Javascript is as follows:
-To be able to create with javascript both .thf and .trf forms dynamically along with every other input/button that is inside each form with clicking the .btndag button (this is an onclick event followed by create.element if I'm not mistaken).
-For the .morehf <input button> have a hide/show toggle function for .trf and anything else inside that form.
-Toggle disabled in the .crf input text boxes with the .edithf <input button>.
-To be able to erase/remove both .thf and .trf forms (their input textboxes AND the buttons .morehf .edithf .erasehf) with the .erasehf <input button>.
-And to be able to save/submit (I am not sure which is the correct term here) any added and completely filled out forms fields (for when we want to send the changes to our database).
Again I would greatly appreciate any help you could give me, and thank you in advance for your time.
You can import jquery into your solution.
For step 1: you do not make sense. Do you mean you want to load data into your form from somewhere to edit data or something? how is this dynamic? It looks like static forms on a page.
For step 2:
<input class="morehf" onclick="toggleTrf()" type="button" value="+/-" />
<script>
function toggleTrf() {
$(".trf").toggle()
}
</script>
step 3:
<input class="edithf" onclick="disableInputs()" type="button" value="Edit" />
<script>
function disableInputs() {
if($(".crf").is(":disabled");){
//jquery 1.6+
$(".crf").prop('disabled', false);
//jquery 1.5 -
$(".crf").removeAttr('disabled');
}
else {
//jquery 1.6+
$(".crf").prop('disabled', true);
//jquery 1.5 -
$(".crf").attr('disabled','disabled');
}
}
</script>
step 4: it is not clear what you mean by erase the form but you can clear the text in the inputs
<input class="erasehf" thpe="reset" onclick="clearInputs()" value="Erase" />
<script>
function clearInputs() {
$("input").val("")
}
</script>
step 5:
<form action="some/path">
<input name="someName" type="text" text="random field" value="1" />
<button type="submit">submit</button>
</form>
That submit button will submit the form to whatever path you specify in your form action. As for saving to the database etc it is impossible to guess what technology you will use to do that.sorry about code formattin im typing on a phone.
I believe I have included everything the OP wanted. The non-jQuery approach (ES6). JSFiddle
First lets add a few helper variables:
let formSets = 0;
let createForm = function(id) {
return `<form data-id='${id}' class="thf">
<input class="morehf" type="button" value="+/-" />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="edithf" type="button" value="Edit" />
<input class="erasehf" type="reset" value="Erase" />
</form>
<form data-id='${id}' class="trf">
<input class="crf" type="text" placeholder="POS" readonly />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
</form>`;
};
Add the onclick event for the "add" function. We have to reassign the click events to the dynamically added elements or we could have done event delegation like I did for the remove button:
document.getElementsByClassName('btndag')[0].onclick = () => {
document.getElementById('a').innerHTML += createForm(++formSets);
for (let ii = 0; ii < formSets; ii++) {
document.getElementsByClassName("morehf")[ii].onclick = () => {
document.getElementsByClassName("trf")[ii].classList.toggle('hide');
}
document.getElementsByClassName("edithf")[ii].onclick = () => {
let form = document.getElementsByClassName("trf")[ii].children;
for (let i = 0; i < form.length; i++) {
let input = form[i];
if (input.disabled == true) {
input.disabled = false;
} else {
input.disabled = true;
}
}
}
}
};
Add the remove button a little differently using event delegation which allows us to target another element based on the parents target:
document.getElementById('a').onclick = function(e) {
let t = e.target;
if (t.className == 'erasehf') {
let me = t.parentNode;
let sib = me.nextElementSibling;
me.parentNode.removeChild(me);
sib.parentNode.removeChild(sib);
}
}
Finally, submit the data. This part is a little more vague simply because I am not exactly sure how you want the data formatted. But here is how you would submit the form using AJAX:
document.getElementsByClassName('btndgu')[0].onclick = function() {
Request("/linkto/save.asp").post({
//datahere
}).then(function () {
//on success
}, function () {
//on failure
});
}
Note that this uses a helper AJAX function that I made:
let Request = function(url, opt) {
// start loader
var AJAX = function(type, url, data, success, failure, cache) {
var InitRequest = new Promise(function(accept, reject) {
var request = new XMLHttpRequest(); // initiate new XMLHttpRequest
var done = false;
var compile = function(data) { //turn the data object into a usable source for the send function
var send = [];
for (var item in data) { // compile all data in "item=data" strings
send.push(item + "=" + encodeURIComponent(data[item]));
}
send = send.join("&"); // combine data to form "item1=data1&item2=dat2&item3=data3"
return send;
};
// if we choose not send any data, then the data variable will take the place of the success variable
// because of this, we have to also shift the failure function
if (typeof data === "function") {
success = data || accept;
failure = success || reject;
data = "";
} else {
success = success || accept;
failure = failure || reject;
data = compile(data);
}
if (type.toUpperCase() == 'POST') {
request.open(type.toUpperCase(), url, true);
// this header allows POST requests to work
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
} else if (type.toUpperCase() == 'GET') {
// for GET requests, we need to put all data in the url
// we would end up with test.php?item1=data1&item2=dat2&item3=data3
request.open(type.toUpperCase(), url + "?" + data, true);
} else {
console.error('Incorrect request type submitted: "' + type + '" is not supported.');
return false;
}
// in order for laravel to properly send ajax requests
request.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onreadystatechange = function() {
if (!done) {
if (request.readyState === 4) { // when the readyState == 4, we have completed the request
if (request.status === 200 || request.status === 0 /*for ff bug*/ ) {
success(request.responseText, request);
} else { //if failed
try {
request.responseJSON = JSON.parse(request.responseText);
} catch (e) {
return false;
}
failure(request);
}
// hide the loader because the request has finished
done = true;
}
}
};
// send off the request
request.send(data);
});
return InitRequest;
};
// The "opt" variable also goes into place as the
// Cache reset
if (opt && typeof opt !== "string" && typeof opt !== "boolean") {
var DEFAULTS = {
type: "GET",
data: {},
cache: false,
success: function() {},
failure: function() {}
};
var o = $.extend(DEFAULTS, opt);
return AJAX(o.type, url, o.data, o.success, o.failure, o.cache);
} else {
return {
post: function(data, success, failure, cache) {
return AJAX("POST", url, data, success, failure, cache);
},
get: function(data, success, failure, cache) {
return AJAX("GET", url, data, success, failure, cache);
}
}
}
}
A little more information about sending data via AJAX
Data in your case should correspond with the ids:
{
0: {
trf: {
input1: "..",
input2: "..",
input3: ".."
}
},
1: {
trf: {
input1: "..",
input2: "..",
input3: ".."
}
}
}
Im trying to create a simple login verification, however the validation function seizes to function when the validation comparison begins, and the console sais that the variable "userName is not defined" although it clearly is.
Can enyone tell me what am i defining wrong?
the angular controller code:
var app = angular.module("LoginApp", []);
app.controller("LoginController", function ($http) {
this.userName = "";
this.password = "";
this.userNameValid = true;
this.passwordValid = true;
/*submit the form*/
this.submit = function () {
alert("submit");
this.validate();
};
/* make sure user name and password has been inserted*/
this.validate = function () {
alert("validate");
var result = true;
this.userNameValid = true;
this.passwordValid = true;
if (this.userName == "") {
alert("username="+userName);
this.userNameValid = false;
result = false;
}
if (this.password == "") {
this.passwordValid = false;
result = false;
}
alert("validuserNameValid==" + userNameValid + " passwordValid==" + passwordValid);
return result;
};
});
the HTML form:
<body ng-app="LoginApp" ng-controller="LoginController as LoginController">
<form role="form" novalidate name="loginForm" ng-submit="LoginController.submit()">
<div id="loginDetails">
<div class="form-group">
<label for="user"> User Name:</label>
<input type="text" id="user" class="form-control" ng-model="LoginController.userName" required />
<span ng-show="LoginController.userNameValid==false" class="alert-danger">field is requiered</span>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" id="password" class="form-control" ng-model="LoginController.password" required />
<span ng-show="LoginController.passwordValid==false" class="alert-danger">field is requiered</span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
{{"entered information:" +"\n"+LoginController.userName+" "+ LoginController.password}}
</div>
</div>
</form>
</body>
the log:
Error: userName is not defined
this.validate#http://localhost:39191/login.js:23:13
this.submit#http://localhost:39191/login.js:11:9
anonymous/fn#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js line 231 > Function:2:292
b#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:126:19
Kc[b]</<.compile/</</e#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:274:195
uf/this.$get</m.prototype.$eval#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:103
uf/this.$get</m.prototype.$apply#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:335
Kc[b]</<.compile/</<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:274:245
Rf#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:37:31
Qf/d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:36:486
Always use this judiciously. I would recommend you to store the reference of this in variable then use it wherever required.
var app = angular.module("LoginApp", []);
app.controller("LoginController", function ($http) {
//Store the reference of this in a variable
var lc = this;
//Use the stored refrence
lc.userName = "";
/* make sure user name and password has been inserted*/
lc.validate = function () {
if (lc.userName == "") {
alert("username="+userName);
lc.userNameValid = false;
result = false;
}
};
});
inside your alert boxes you have not mentioned this.userName try removing the alert boxes or change them.
I am playing around a bit with Parse.com and I am trying to send HTML form's content to Parse.com
I am kind of a Javascript noob so for some reason I cannot find a way to pass a variable I got from the form's input to Parse.com for processing.
Here's my code:
<div class="main">
<form action="">
<label>Insert your ingridient :</label>
<input type="text" id="text" name="name" value="" />
<input type="button" id="text_value" value="Get Value"/>
<script type="text/javascript">
$(document).ready(function() {
$('#text_value').click(function() {
var text_value = $("#text").val();{
alert(text_value);
}
});
});
Parse.initialize("myAPIKey", "myAPIKey");
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
name: text_value,
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
}
});
</script>
You should wrap the code that does the saving inside a function, then call it when the user clicks the button. You have a few errors with your {} brackets as well. Indenting your code when writing it will help you avoid that.
<div class="main">
<form action="">
<label>Insert your ingridient :</label>
<input type="text" id="text" name="name" value="" />
<input type="button" id="text_value" value="Get Value"/>
<script type="text/javascript">
$(document).ready(function() {
$('#text_value').click(function() {
var text_value = $("#text").val();
save(text_value);
});
Parse.initialize("myAPIKey", "myAPIKey");
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
function save(value) {
gameScore.save({name: text_value}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
}
});
};
};
</script>