Passing form's input to Parse.com - javascript

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>

Related

Pass data to post.php in the background form fields

I have this script that works well for sending a message from a form via post. But I would like to add more information from the form to be sent via the script but can't get it working?! Do I have to have have one $.post("post.php" .. for every input? Thanks a million.
--- THIS ONE IS SENT FINE TO post.php --
<input name="usermsg" type="text" id="usermsg" />
--- WOULD LIKE TO ADD THESE TO THE SCRIPT --
<input type="hidden" name="request" value="1" />
<input type="hidden" name="sentby" value="2" />
<input type="hidden" name="sentto" value="3" />
$(document).ready(function () {
$("#submitmsg").click(function () {
var clientmsg = $("#usermsg").val();
$.post("post.php", { text: clientmsg });
$("#usermsg").val("");
return false;
});
});
$(document).ready(function () {
$("#submitmsg").click(function () {
var clientmsg = $("#usermsg").val();
var request = $("#request").val();
var sentby = $("#sentby").val();
var sentto = $("#sentto").val();
$.post("post.php",
{
text: clientmsg,
request: request,
sentby: sentby,
sentto: sentto,
},
function(result){
// you can do anything you want with result
});
$("#usermsg").val("");
return false;
});
});

TypeError: document.getElementById(...) is null but the id is correct as i have similarly called another form also

I am trying to execute a function but this error keeps on coming in the console
TypeError: document.getElementById(...) is null
fetch http://localhost:8082/app.js:28368
Here is the HTML code
<form id="player2">
<div class="form-group">
<label>Player 2 - From address:</label>
<input type=" type" class="form-control" id="fromAddress2">
</div>
<input type="submit" value="player2" class="btn-primary" />
</form>
Here is the App.js
function fetch(){
document.getElementById("player2").addEventListener("submit", function(e){
e.preventDefault();
var fromAddress2 = document.getElementById("#player2 #fromAddress2").value;
console.log(fromAddress2);
OraclizeContract.deployed().then(function(instance) {
console.log("Initializing");
instance.deposit({from: fromAddress2,
gas: 3000000,
value: web3.toWei(1, 'ether')}) //betAmount is a input box and fetching its value into betamount variable and passing it over here
.then(function(v){
console.log(v);
console.log("Function Executed");
});
}).then(function() {
console.log("Testing");
}).catch(function(e) {
console.log(e);
});
})
}
I have checked the ids but they are correct, cannot figure out why this is not working
Any help is highly appreciated
var fromAddress2 = document.getElementById("#player2 #fromAddress2").value;
should be instead:
var fromAddress2 = document.querySelector("#player2 #fromAddress2").value;

2CheckOut - TwoCheckoutException: Bad request - parameter error

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

Uncaught ReferenceError: submitToAPI is not defined at HTMLButtonElement.onclick

I am creating a form filling website it should return alert message if contact,email is not up to our standard.
But I am getting this error Uncaught ReferenceError: submitToAPI is not defined at HTMLButtonElement.onclick
var URL is I am passing these data to AWS API gateway and trigger a lambda function.
form html code
<h4>Name:</h4>
<input type="text" style="height:35px;" id="name-input" placeholder="Enter name here…" class="form-control" style="width:100%;" /><br/>
<h4>Company Name:</h4>
<input type="text" style="height:35px;" id="cname-input" placeholder="Enter name here…" class="form-control" style="width:100%;" /><br/>
<h4>Contact Number:</h4>
<input type="phone" style="height:35px;" id="phone-input" placeholder="Enter phone number" class="form-control" style="width:100%;"/><br/>
<h4>Email:</h4>
<input type="email" style="height:35px;" id="email-input" placeholder="Enter email here…" class="form-control" style="width:100%;"/><br/>4>
<div class="g-recaptcha" data-sitekey="6Lc7cVMUAAAAAM1yxf64wrmO8gvi8A1oQ_ead1ys" class="form-control" style="width:100%;"></div>
<button type="button" onClick="submitToAPI(event)" class="btn btn-lg" style="margin-top:20px;">Submit</button>
javascript
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
function submitToAPI(e) {
e.preventDefault(e);
var URL = "https://abc1234.execute-api.us-east-1.amazonaws.com/01/contact";
var e_name = /[A-Za-z]{1}[A-Za-z]/;
if (!e_name.test($("#name-input").val())) {
alert ("Name can not less than 2 char");
return;
}
var e_cname = /[A-Za-z]{1}[A-Za-z]/;
if (!e_cname.test($("#cname-input").val())) {
alert ("Name can not less than 2 char");
return;
}
var e_phone = /[0-9]{10}/;
if (!e_phone.test($("#phone-input").val())) {
alert ("Please enter valid mobile number");
return;
}
if ($("#email-input").val()=="") {
alert ("Please enter your email id");
return;
}
var e_email = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,6})?$/;
if (!e_email.test($("#email-input").val())) {
alert ("Please enter valid email address");
return;
}
var e_name = $("#name-input").val();
var e_cname = $("#cname-input").val();
var e_phone = $("#phone-input").val();
var e_email = $("#email-input").val();
var data = {
name : e_name,
cname : e_cname,
phone : e_phone,
email : e_email,
};
$.ajax({
type: "POST",
url : "https://abc1234.execute-api.us-east-1.amazonaws.com/01/contact",
dataType: "json",
crossDomain: "true",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function () {
// clear form and show a success message
alert("Successfull");
document.getElementById("contact-form").reset();
location.reload();
},
error: function () {
// show an error message
alert("There is some issue with our servers please contact our landline for enquiry");
}});
}
</script>
You are using the script tag with a src attribute, your browser is only executing the remote JS (Jquery)
Create a new script tag without the src and add your code in this new block!
Correct way is to first load jQuery as your script is dependent on it.
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
</script>
After that you can include your script
<script>
$(document).ready(function () {
function submitToAPI(e) {
// your code
}
});
</script>
Make sure jQuery is properly loaded into your page. Check network tab in dev console, make sure there is no "404".
$(document).ready(function () {
// This code is being loaded after jQuery has been initialized
});

jQuery adding variable content into DIV

I am creating contact form on my website, but i got stuck. I don't know how to put content from variable after each inputs on my website. I can show them into console.log and works perfect but i don't know how to put it on website.
Here's the code:
(function($) {
$(document).ready(function() {
var form = $(".contact_form"),
fields = $("[data-error]");
fields.on("click", function() {
$(this).removeAttr('placeholder');
});
fields.on("blur", function() {
var field = $(this);
field.toggleClass("form_error", $.trim(field.val()) === "");
});
form.on("submit", function(e) {
var hasErrors = false;
fields.each(function(i, elem) {
var field = $(elem),
empty = $.trim(field.val()) === "",
errors = field.data("error");
console.log(errors);
// HERE IS ERROR VAR
// sth here to put it into html
field.toggleClass("form_error", empty);
if (empty) {
hasErrors = true;
}
});
if (!hasErrors) {
form.submit();
} else {
e.preventDefault();
}
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" accept-charset="utf-8" class="contact_form">
<input type="text" placeholder="Imię" data-error="Podaj imię">
<input type="text" placeholder="Nazwisko" data-error="Podaj nazwisko">
<input type="email" placeholder="E-mail" data-error="Podaj poprawny adres e-mail">
<input type="text" placeholder="Kontakt" data-error="Podaj poprawny numer telefonu">
<textarea name="message" class="textarea_field" placeholder="WIADOMOŚĆ" data-error="Wpisz treść wiadomości"></textarea>
<button type="submit" class="przycisk">Wyślij</button>
</form>
Firstly note that presumably you're trying to check that the fields all have a value. If so, you should put the error message generation logic in the if (empty) code block.
To actually create the HTML for the messages you can use the after() method to insert the error messages after the related input element. If you also wrap the errors in an element, such as a span, which has a class you can easily use that to remove() the elements when the form is submit to be re-evaluated. Try this:
(function($) {
$(document).ready(function() {
var form = $(".contact_form"),
fields = $("[data-error]");
fields.on("click", function() {
$(this).removeAttr('placeholder');
});
fields.on("blur", function() {
var field = $(this);
var valid = $.trim(field.val()) !== "";
field.toggleClass("form_error", !valid).next('span.form_error').remove();
if (!valid)
field.after('<span class="form_error">' + $(this).data('error') + '</span>'); // add new error messages
});
form.on("submit", function(e) {
var hasErrors = false;
$('span.form_error').remove(); // Remove any old errors when submitting the form
fields.each(function(i, elem) {
var field = $(elem),
empty = $.trim(field.val()) === "",
errors = field.data("error");
if (empty) {
hasErrors = true;
field.after('<span class="form_error">' + errors + '</span>'); // add new error messages
field.toggleClass("form_error", empty);
}
});
if (!hasErrors) {
form.submit();
} else {
e.preventDefault();
}
});
});
})(jQuery);
span.form_error {
color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" accept-charset="utf-8" class="contact_form">
<input type="text" placeholder="Imię" data-error="Podaj imię">
<input type="text" placeholder="Nazwisko" data-error="Podaj nazwisko">
<input type="email" placeholder="E-mail" data-error="Podaj poprawny adres e-mail">
<input type="text" placeholder="Kontakt" data-error="Podaj poprawny numer telefonu">
<textarea name="message" class="textarea_field" placeholder="WIADOMOŚĆ" data-error="Wpisz treść wiadomości"></textarea>
<button type="submit" class="przycisk">Wyślij</button>
</form>
Use text() for adding string to element or html() for adding html code.
Example:
var text = 'hello world';
$('div#textHere').text(text);
var htmlCode = "<strong>Hello</strong> World";
$('div#htmlHere').html(htmlCode);
Documentation for text() and for html().
When you want to get form field values you use $('#id').val(); the val will get value from form fields. And then you can use $('#id').html('Enter val here') that's it.
use can use text() or html()
Different:
1)If you retrieve text only, u can use text()
2)If you retrieve html element with text, then u can use html();
Eg 1 : -
var text1="hello world";
$(".text").text(text1) ==> hello world
$(".text").html(text1) ==> hello world
Eg 2 : -
var text2="<h1>hello world</h1>";
$(".text").text(text2) ==> '< h1>hello world< /h1>'
$(".text").html(text2) ==>hello world`

Categories