I can't get the values of these three fields; it only returns an empty value (a space).
The ids are correctly set in the form.
<script>
const data = {
id: document.getElementById('idbook').value,
name: document.getElementById('namebook').value,
price: document.getElementById('pricebook').value
};
function myFunction(){
const http = new easyHTTP;
http.put('https://otg0gf6qw5.execute-api.us-east-2.amazonaws.com/books',
data, function(err, post){
if(err) {
console.log(err);
} else {
console.log(post);
}
});
</script>
<!DOCTYPE html>
<html>
<body>
<div class="container">
<form method="post" id="save" action="javascript:myFunction()">
<h1>Insert Book</h1>
<div class="field">
<label for="id">ID Book:</label>
<input type="text" id="idbook" name="id"/>
<small></small>
</div>
<div class="field">
<label for="id">Name Book:</label>
<input type="text" id="namebook" name="nameBook"/>
<small></small>
</div>
<div class="field">
<label for="id">Price Book:</label>
<input type="text" id="pricebook" name="priceBook"/>
<small></small>
</div>
<div class="field">
<button type="submit" class="full">SAVE BOOK</button>
</div>
</form>
</div>
When I enter the values, and click on SAVE I get an empty json, i.e .:
{"id":"","name":"","price":""}
with error:
"One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: id"
The problem is that you are getting the values from the input fields as soon as the script runs, so you will get empty strings because the inputs at that point are empty.
To get the input values after the form is submitted, put the data variable inside the myFunction() method, it's important to read the values right before sending the data.
Example
<script>
function myFunction() {
const data = {
id: document.getElementById('idbook').value,
name: document.getElementById('namebook').value,
price: document.getElementById('pricebook').value
};
const http = new easyHTTP;
http.put('https://otg0gf6qw5.execute-api.us-east-2.amazonaws.com/books', data, function(err, post) {
if(err) {
console.log(err);
} else {
console.log(post);
}
});
};
</script>
I don't know if this is what you mean, but I did let the data save in the console log when you press submit
<div class="container">
<form method="post" id="save" action="javascript:myFunction()">
<h1>Insert Book</h1>
<div class="field">
<label for="id">ID Book:</label>
<input type="text" id="idbook" name="id"/>
<small></small>
</div>
<div class="field">
<label for="id">Name Book:</label>
<input type="text" id="namebook" name="nameBook"/>
<small></small>
</div>
<div class="field">
<label for="id">Price Book:</label>
<input type="text" id="pricebook" name="priceBook"/>
<small></small>
</div>
<div class="field">
<button type="submit" class="full">SAVE BOOK</button>
</div>
</form>
<script>
function myFunction(){
const data = {
id: document.getElementById('idbook').value,
name: document.getElementById('namebook').value,
price: document.getElementById('pricebook').value
};
console.log(data);
}
</script>
</div></body></html>
Related
When my login credentials are prefilled by my browser (chrome) my fetch function doesn't send the values
html
<div class='login-frame'>
<h3>Bienvenue</h3>
<div class='form'>
<div class='input-handler'>
<label for='login'>Login</label>
<input type='text' id='login' name='login' autocomplete='on'>
</div>
<br>
<div class='input-handler'>
<label for='pass'>Mot-de-passe</label>
<input type='password' id='pass' name='pass' autocomplete='on'>
</div>
<br>
<button id='loginbutton'>CONNEXION</button>
</div>
</div>
JS
window.onload = function() {
var pass = document.getElementById('pass'),
login = document.getElementById('login'),
loginButton = document.getElementById('loginbutton');
loginbutton.onclick = (e)=> {
var creds = {
login: login.value,
pass: pass.value
}
fetch('functions/log.php', {
method: "POST",
header: {"Content-type": "application/json; charset=UTF-8"},
body: JSON.stringify(creds)
});
}
PHP
$pos = json_decode(file_get_contents('php://input', true));
echo var_dump($pos);
If I type anything, it returns
object(stdClass)#3 (2) {
["login"]=>
string(3) "qfz"
["pass"]=>
string(5) "zfqzf"
}
If I use the browser prefill, it returns
NULL
It was a mistake,
as #CBroe said, it was a security problem. Changing my html to a proper form make it works as it should
<form class='login-frame' method='post' action='#'>
<div class='login-logo'><img src='bs/img/logo_b.svg'></div>
<h3>Bienvenue</h3>
<div class='form'>
<div class='input-handler'>
<label for='login'>Login</label>
<input type='text' id='login' name='login' autocomplete='on'>
</div>
<br>
<div class='input-handler'>
<label for='pass'>Mot-de-passe</label>
<input type='password' id='pass' name='pass' autocomplete='on'>
</div>
<br>
<button type='submit' id='loginbutton'>CONNEXION</button>
</div>
</form>
The Error I am getting when I try to checkout after putting card details:
Invalid source object: must be a dictionary or a non-empty string. See API docs at https://stripe.com/docs'
Here I taking all the card information:
<form method="post" action="{{route('checkout')}}" enctype="multipart/form-data" id="checkout-form">
#csrf
<div class="col-sm-3">
<div class="form-group">
<label>Card Number*</label>
<input type="text" class="form-control" name="card-number" id="card-number" placeholder="4111 1111 1111 1111"> </div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label>Card CVC*</label>
<input type="text" class="form-control" name="card-cvc" id="card-cvc" placeholder="111"> </div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label>Card Expiry Month*</label>
<input type="text" class="form-control" name="card-month" id="card-month" placeholder="12"> </div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label>Card Expiry Year*</label>
<input type="text" class="form-control" name="card-expiry-year" id="card-expiry-year" placeholder="2020"> </div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Card Name*</label>
<input type="text" class="form-control" name="card-name" id="card-name" placeholder="John"> </div>
</div>
</form>
I am sending the Token through script:
<script>
var stripe = Stripe('test_key');
var $form = $('#checkout-form');
$form.submit(function (event) {
$('charge-error').addClass('hidden');
$form.find('button').prop('disabled' , true);
Stripe.card.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val(),
name: $('.card-name').val(),
}, stripeResponseHandler);
return false;
});
function stripeResponseHandler(status, response) {
var $form = $('#checkout-form');
if (response.error){
$('.charge-error').removeClass('hidden');
$('.charge-error').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
var token = response.id;
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
//Submit the form:
$form.get(0).submit();
}
}
and this is the controller Function:
$stripe = new \Stripe\StripeClient('secret_test_key');
try {
$charge = $stripe->charges->create([
"amount" => 6800,
"currency" => "usd",
"source" => $request->input('stripeToken'),
"description" => "Charge for test#expamle.com"
]
);
} catch (\Exception $e) {
return redirect()->route('checkout')->with('error', $e->getMessage());
}
If the replace the "source" => $request->input('stripeToken'), with "source" => "visa", then the code works fine.
Why am I getting this error? Please help.
If you're using Stripe.js v2 you need to set the publishable key like this:
Stripe.setPublishableKey('pk_test_xxx');
not what you're currently doing:
var stripe = Stripe('test_key');
(see https://stripe.com/docs/stripe-js/v2#setting-publishable-key)
At the line where you have "source" => $request->input('stripeToken') try to print that input out before carrying out the charge to see if the value is actually there or is in a valid format. If the value is not there ensure the variable you have called token assigned to the hidden field actually has the correct value.
I made some little project with adding element to DOM. It's working but I don't know how to clear form after submit. I need to assign a blank value? At what point? Sorry, Im new, please don't bite. Thanks.
const addElement = (e, node, txt, attr, value) => {
e.preventDefault();
const element = document.createElement(node);
if(txt){
const text = document.createTextNode(txt);
element.appendChild(text);
}
if(attr){
element.setAttribute(attr, value)
}
document.querySelector('.content').appendChild(element);
}
const addForm = document.querySelector('.form--add');
addForm.addEventListener('submit', (e) => addElement(
e,
addForm.elements.node.value,
addForm.elements.text.value,
addForm.elements.attr.value,
addForm.elements.value.value,
));
<div class="form-container">
<form class="form form--add">
<h1 class="form__title">Add element to DOM</h1>
<input type="text" class="form__input" name="node" placeholder="element html" required>
<input type="text" class="form__input" name="text" placeholder="txt in element html">
<input type="text" class="form__input" name="attr" placeholder="attr" required>
<input type="text" class="form__input" name="value" placeholder="attr value" required>
<button class="form__button">Add element</button>
</form>
<form class="form form--search">
<h1 class="form__title">Search DOM</h1>
<input type="text" class="form__input" placeholder="szukana nazwa elementu" required>
<input type="submit" class="form__button" value="znajdź i pokaż informacje">
</form>
</div>
<div class="result"></div>
<div class="content"></div>
<footer class="footer">Stopka</footer>
<script src="main.js"></script>
Thank you
Try addForm.reset()
or
declare an id for suppose form_id then paste below code after submit
document.getElementById("form_id ").reset();
addForm.addEventListener('submit', (e) => addElement(
e,
addForm.elements.node.value,
addForm.elements.text.value,
addForm.elements.attr.value,
addForm.elements.value.value,
addForm.getElementsByTagsName('input').forEach(el => {
el.value = ''
})
));
I want to apply required field validation on text box group in which at least one text box group must contain value.
in bellow image, details of at least one bank must be filled.
I have used jquery-form-validator plugin from http://www.formvalidator.net/#custom-validators and created custome validator as bellow, but Its not working.
$("#txtBankDetails")
.valAttr('error-msg', 'select atlest 1 bankname.');
$.formUtils.addValidator({
name: 'data-text-group',
validatorFunction: function (value, $el, config, language, $form) {
debugger
var isValid = true,
// get name of element. since it is a checkbox group, all checkboxes will have same name
elname = $el.attr('data-text-group'),
// get checkboxes and count the checked ones
$textBoxes = $('input[type=textbox][data-text-group^="' + elname + '"]', $form),
nonEmptyCount = $textBoxes.filter(function () {
return !!this.value;
}).length;
alert(nonEmptyCount);
if (nonEmptyCount == 0) {
isValid = false;
}
}
});
// Setup form validation only on the form having id "registration"
$.validate({
form: '#registration',
modules: 'date, security, file, logic',
validateOnBlur: true,
showHelpOnFocus: true,
addSuggestions: true,
onModulesLoaded: function () {
console.log('All modules loaded!');
},
onSuccess: function ($form) {
form.submit();
alert("sucess")
return false;
},
onError: function () {
alert("Error")
}
});
html code is,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/theme-default.min.css"
rel="stylesheet" type="text/css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<form id="registration" method="post" action="#Url.Action("NewRegistration", "StaticPage")" enctype="multipart/form-data" class='has-validation-callback'>
<div class="container">
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname1" data-text-group="BankName" placeholder="01. BANK NAME" data-validation-error-msg="select atlest 1 bankname.">
</div>
<div class="col-md-4">
<input class="nwresmainfild" name="BankACNo1" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input class="nwresmainfild" name="BankAddress1" placeholder="BANK ADDRESS">
</div>
</div>
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname2" data-text-group="BankName" placeholder="01. BANK NAME" data-validation-error-msg="select atlest 1 bankname.">
</div>
<div class="col-md-4">
<input name="BankACNo2" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input name="BankAddress2" placeholder="BANK ADDRESS">
</div>
</div>
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname3" data-text-group="BankName" placeholder="03. BANK NAME" >
</div>
<div class="col-md-4">
<input name="BankACNo3" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input name="BankAddress3" placeholder="BANK ADDRESS">
</div>
</div>
</div>
<input value="PROCESS & PRINT" class="green-btn uppercase" type="submit" id="btnSubmit" />
</form>
I want to retrieve 2 input field values from one of the 2 forms in my jsp file and use that value in my second form. So I used javascript to get the values from the first form and display it in a hidden input field in the second form so that I could use those values, but it is giving me a number format exception so I'm guessing the values from the first form is not correctly getting passed to the second form. Here is my code:
jsp file:
<script>
function getNumOfDays(){
var numOfDays = document.getElementById("numOfDays").value;
document.getElementById("hiddenNumDays").value = numOfDays;
}
function getTotalMiles(){
var totalMiles = document.getElementById("totalMile").value;
document.getElementById("hiddenTotalMiles").value = totalMiles;
}
function getTotalDue(){
var HtotalDue = document.getElementById("totalDue").value;
document.getElementById("hiddentTotalDue").value = HtotalDue;
}
</script>
First Form
<form class="form-horizontal" name="selectVehicleForm" action="SelectVehicle">
<div class="form-group">
<label class="col-md-5 control-label">Number of Days Renting:</label>
<div class="col-md-3">
<input class="form-control" type="text" id="numOfDays" name="numOfDays" disabled>
</div>
</div>
<div class="form-group">
<label class="col-md-5 control-label">Total Miles:</label>
<div class="col-md-3">
<input class="form-control" type="text" name="totalMile" id="totalMile" placeholder="approximate">
</div>
</div>
<div class="form-group">
<label class="col-md-5 control-label">Total Amount Due: $</label>
<div class="col-md-3">
<input class="form-control" type="text" name="totalDue" id="totalDue" disabled>
</div>
</div>
</form>
Second Form
<input type="text" name="hiddenNumDays" id="hiddenNumDays" disabled>
<input type="hidden" name="hiddenTotalMiles" id="hiddenTotalMiles" disabled>
<input type="hidden" name="hiddentTotalDue" id="hiddentTotalDue" disabled>
Serlvet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Payment paymentInfo = new Payment();
paymentInfo.setId(10);
paymentInfo.setFirstName(request.getParameter("firstName"));
paymentInfo.setLastName(request.getParameter("lastName"));
paymentInfo.setAddress(request.getParameter("address"));
paymentInfo.setAptSuit(request.getParameter("aptNum"));
paymentInfo.setCity(request.getParameter("city"));
paymentInfo.setState(request.getParameter("state"));
paymentInfo.setZipcode(request.getParameter("zipCode"));
paymentInfo.setPhoneNum(request.getParameter("phoneNum"));
paymentInfo.setEmail(request.getParameter("email"));
paymentInfo.setCreditCardType(request.getParameter("card"));
paymentInfo.setCreditCardNum(Integer.parseInt(request.getParameter("cardNumber")));
paymentInfo.setExpirationDate(request.getParameter("expMonth"));
paymentInfo.setCvCode(Integer.parseInt(request.getParameter("cvCode")));
paymentInfo.setNumOfDays(Integer.parseInt(request.getParameter("hiddenNumDays")));
paymentInfo.setTotalDue(request.getParameter("hiddenTotalDue"));
int result = RentService.insertPaymentDB(paymentInfo);
if(result > 0)
{
int vehicleID = Integer.parseInt(request.getParameter("id"));
InventoryService.updateVehicleAvailabilty(vehicleID);
response.sendRedirect("RentCar");
}
else
{
response.sendRedirect("failure.jsp");
}
}
why don't you put the value you take from either of the two forms in session like this
request.getsession.setAttribute("name", value);
then you can access it
String value=session.getAttribute("name").toString();