I'm using this code to send data to my sheet.
For The FullName, Phone, Address, ..., data is sent with no problem.
But I'm blocked to split and push value input radio data and send it to my sheet.
Example if the second input of radio is selected ( sku_order_2|quantity2|price22 )
sku = sku_order_2 quantity = quantity2 price = price22
const scriptURL = 'https://script.google.com/........'
const form = document.forms['formName']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
})
<form action="" name="formName" method="post" id="formName" data-redirect="" class="form">
<input id="order1" class="variant" type="radio" name="order" value="sku_order_1|quantity1|price15" hidden="" checked="">
<input id="order2" class="variant" type="radio" name="order" value="sku_order_2|quantity2|price22" hidden="">
<input id="order2" class="variant" type="radio" name="order" value="sku_order_3|quantity3|price26" hidden="">
<input id="fullname" class="input" type="text" placeholder="Fullname" name="fullname" required="">
<input id="phone" class="input" type="number" placeholder="Phone" name="phone" required="">
<input id="address" class="input" type="text" placeholder="Address" name="address" required="">
</form>
Use the FormData methods (https://developer.mozilla.org/en-US/docs/Web/API/FormData)
You can get the order value with formData.get('order')
than you can split (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) the string and use the result to append the fields: sku, quantity, price.
const scriptURL = 'https://script.google.com/........'
const form = document.forms['formName']
form.addEventListener('submit', e => {
e.preventDefault()
const formData = new FormData(form)
const order = formData.get('order').split('|') // Split the string using '|' into an array [sku, quantity, price]
formData.append('sku', order[0])
formData.append('quantity', order[1])
formData.append('price', order[2])
formData.delete('order')
fetch(scriptURL, { method: 'POST', body: formData})
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
})
<form action="" name="formName" method="post" id="formName" data-redirect="" class="form">
<div>
<input id="order1" class="variant" type="radio" name="order" value="sku_order_1|quantity1|price15" checked=""> 1
<input id="order2" type="radio" class="variant" name="order" value="sku_order_2|quantity2|price22"> 2
<input id="order3" class="variant" type="radio" name="order" value="sku_order_3|quantity3|price26"> 3
</div>
<input id="fullname" class="input" type="text" placeholder="Fullname" name="fullname" required="">
<input id="phone" class="input" type="number" placeholder="Phone" name="phone" required="">
<input id="address" class="input" type="text" placeholder="Address" name="address" required="">
<input type="submit" value="Send">
</form>
If you want to split the order property, you can do the following:
Get the order values from formData
Split the retrieved order value by separator |
Map the exploded order values to their representatives sku, quantity and price
add sku, quantity and price to formData
See this fiddle: https://jsfiddle.net/Lxujkotp/1/
Extended Code:
form.addEventListener('submit', e => {
var data = new FormData(form);
var order = data.get('order');
var orderParts = order.split('|');
// WARNING: if the "order values" does not have a fix ordering, map the values here more sophisticated!
var sku = orderParts[0];
var quantity = orderParts[1];
var price = orderParts[2];
e.preventDefault();
data.delete('order');
// approach 1: plain
data.set('sku', sku);
data.set('quantity', quantity);
data.set('price', price);
// alternative approach 2: nested
// data.set('order', JSON.stringify({
// sku: sku,
// quantity: quantity,
// price: price
// }));
fetch(scriptURL, { method: 'POST', body: data })
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
});
Related
I'm working with DOM and web API to POST some information about the company like name, worker's name.
But when I write something in the input DOM can't reach the value and return empty so I post an empty object.
That looks like :
adress: ""
companyName: ""
contactName: ""
contactTitle: ""
My form block:
<form>
<div class="form-group">
<label for="">Company Name</label>
<input
type="text"
class="form-control"
id="companyName"
placeholder="Company Name!"
/>
</div>
<div class="form-group">
<label for="">Contact Name</label>
<input
type="text"
class="form-control"
id="contactName"
placeholder="Contact Name!"
value=""
/>
</div>
<div class="form-group">
<label for="">Contact Title</label>
<input
type="text"
class="form-control"
id="contactTitle"
placeholder="Contact Title!"
/>
</div>
<div class="form-group">
<label for="">Country</label>
<input
type="text"
class="form-control"
id="inputCountry"
placeholder="Country!"
/>
</div>
</form>
And my JS code:
'use strict';
let inputCompanyName = document.getElementById('companyName');
let inputContactName = document.getElementById('contactName');
let inputContactTitle = document.getElementById('contactTitle');
let country = document.getElementById('inputCountry');
const btnSubmit = document.getElementById('submit');
let newCompany = {
companyName: inputCompanyName.value,
contactName: inputContactName.value,
contactTitle: inputContactTitle.value,
adress: country.value,
};
btnSubmit.addEventListener('click', e => {
e.preventDefault();
axios
.post('https://northwind.vercel.app/api/suppliers', newCompany)
.then(res => {
console.log('Response', res.data);
alert('Success!');
});
});
I tried innerHTML and innerText and form method but I cant solve this problem.
You're reading the values immediately upon loading the page, long before the user has had a chance to enter any values.
Instead, read the values in the click event:
btnSubmit.addEventListener('click', e => {
let newCompany = {
companyName: inputCompanyName.value,
contactName: inputContactName.value,
contactTitle: inputContactTitle.value,
adress: country.value,
};
// the rest of the click handler logic...
});
function checkRegisterError() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://ipaddressandport/users/register");
xhr.onload = () => {
console.log("tes");
if (xhr.status === 400) {
console.log("rip");
}
};
xhr.send();
}
const signupBtn = document.querySelector(".signup-form-btn");
if (signupBtn) {
signupBtn.addEventListener("click", () => {
console.log("ok");
checkRegisterError();
});
}
I'm using nodejs and express. So I have this applied on my register button which is also a type submit for a form with an action of /users/register. On my node I have this code which is registered to /users/register:
exports.addUser = (request, respond) => {
if (
!request.body.firstName ||
!request.body.lastName ||
!request.body.email ||
!request.body.username ||
!request.body.password ||
!request.body.gender ||
!request.body.mobileNumber ||
!request.body.address
) {
respond.status(400).send("error empty input etc etc");
} else {
db.execute(
"INSERT INTO users(firstName, lastName, email, username, password, gender, mobileNumber, address, profilePictureUrl) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
[
request.body.firstName,
request.body.lastName,
request.body.email,
request.body.username,
request.body.password,
request.body.gender,
request.body.mobileNumber,
request.body.address,
"https://www.eurogeosurveys.org/wp-content/uploads/2014/02/default_profile_pic.jpg",
]
)
.then((result) => {
console.log(result);
respond.redirect("/");
})
.catch((err) => console.log(err));
}
};
The problem is whenever I press register the forms goes to the route and it will be a blank page of whatever I sent, and there will be no logged output. I want to change certain element properties depending on what the message and status code is. How could I do that? Why am I getting directed to an empty page with the text I sent?
<form class="sign-up-form" action="/users/register" method="POST">
<div class="nav-name">
<input name="firstName" type="text" class="input first-name" placeholder="First name">
<input name="lastName" type="text" class="input last-name" placeholder="Last name">
</div>
<input name="email" type="text" class="input email" placeholder="Email">
<input maxlength="16" name="username" type="text" class="input username" placeholder="User ID">
<div class="password-container">
<input maxlength="16" name="password" type="password" class="input password" placeholder="Password">
<label class="toggle-password" for="toggle-password-register">
<i class="show-password fas fa-eye"></i>
<i class="hide-password fas fa-eye-slash"></i>
</label>
<input id="toggle-password-register" type="checkbox" class="toggle-password__input">
</div>
<input name="gender" type="text" class="input gender" placeholder="Gender">
<input name="mobileNumber" type="text" maxlength="8" class="input mobile-number"
placeholder="Mobile number">
<input name="address" type="text" class="input address" placeholder="Address">
<button type="submit" class="form-btn signup-form-btn">Sign up</button>
</form>
You are getting redirected to empty page because you have written response.redirect('/') , you should check if Db operation is successful then according to that send response to user .
I'm new to programming and I'm using google spreadsheets to receive data from a simple registration form on my static site. Everything is working but I would like to reset the form data after sending the data. I already researched right here in the forum and I did not find any solution that did not erase the data for sending in the reset.
<script>
const scriptURL = 'url-sheet'
const form = document.forms['submit-to-google-sheet']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
})
</script>
<form class="apply" id="apply" name="submit-to-google-sheet">
<div class="j-row apply-field">
<div class="j-col j-col-3">
<label for="Gamertag">Gamertag <span class="gold" title="Required field">*</span></label>
</div>
<div class="j-col j-col-8 push-1">
<input type="text" name="gamertag" placeholder="gamertag" maxlength="12" required>
</div>
</div>
<div class="j-row apply-field">
<div class="j-col j-col-3">
<label for="Discord">Discord <span class="gold" title="Required field">*</span></label>
</div>
<div class="j-col j-col-8 push-1">
<input type="text" name="discord" placeholder="usuário" maxlength="32" required>
<span class="gold">#</span>
<input type="number" name="id" placeholder="1234" maxlength="6" required>
</div>
</div>
<div class="j-row apply-field">
<div class="j-col j-col-3">
<label for="Refferal">Reference?</label>
</div>
<div class="j-col j-col-8 push-1">
<input type="text" name="ref" placeholder="Name" maxlength="20">
</div>
</div>
<input type="text" name="submit" style="display:none" />
<div class="j-row apply-field">
<div class="j-col j-col-12">
<button class="button full-width black" type="submit">Submit</button>
</div>
</div>
</form>
To set the form back to its initial state call reset() on it. Given your logic it would make sense to do this after the AJAX request was successful, so place the call in the then() handler function:
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)}).then(response => {
console.log('Success!', response)
form.reset();
}).catch(error => console.error('Error!', error.message))
})
Add this to your javascript:
$( '#apply' ).each(function(){
this.reset();
});
try document.getElementById("apply").reset();
<script>
const scriptURL = 'url-sheet'
const form = document.forms['submit-to-google-sheet']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
document.getElementById("apply").reset();
})
</script>
Am new in javascript , and am trying to POST data with an API endpoint but data is not posting , I have printed in the console , but I see Slow network is detected. See https://www.chromestatus.com/feature/5636954674692096 for more details. Fallback font will be used while loading: https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0 in Google chrome.
But internet connection is good and stable.
This is my vanilla javascript for posting data :
function onSignUp() {
signupform
var email = document.signupform.email_edt.value;
var driver_rb = document.getElementById("driver_rb").checked;
var password_edt = document.signupform.password_edt.value;
var r_password_edt = document.signupform.r_password_edt.value;
var url = 'https://tuvuge-app.herokuapp.com/api/v1/signup';
//var data = {username: 'example'};
var data = {
username: email,
email: email,
password: password_edt,
isDriver: 'True'
};
fetch(url, {
method: 'POST',
body: JSON.stringify(data), // data can be `string` or {object}!
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Then I attached the onSignUp() function to the button in html as below :
<form class="admin-modal-content" name="signupform" onSubmit="onSignUp();" action="index.html" method="post">
<div class="container">
<h4>Sign Up</h4>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="email">
<b>Email</b>
</label>
<input type="email" placeholder="you#example.com" id="email_edt" name="email_edt" required>
<label for="email">
<b>Select an Option</b>
</label>
<p>
<input type="radio" name="driver_rb" value="driver" id="driver_rb">
<label>Driver</label>
</p>
<p>
<input type="radio" name="passenger_rb" id="passenger_rb" value="passenger">
<label>Passenger</label>
</p>
<label for="psw">
<b>Password</b>
</label>
<input type="password" placeholder="Enter Password" id="password_edt" name="password_edt" required>
<label for="psw-repeat">
<b>Repeat Password</b>
</label>
<input type="password" placeholder="Repeat Password" id="r_password_edt" name="psw-r_password_edt" required>
<div class="clearfix">
<button type="submit" class="btn">Sign Up</button>
</div>
</form>
What am I missing ,because the endpoint has a message it brings when there's a success or failure of data posting , but I see the above message.
What am I missing?
Hello I use the jquery library for the first time.
Jquery:
function habdleProductSubmitRequest(event) {
//no reload page
event.preventDefault()
var productId = $(this).find('[name="id"]').val();
var productName = $(this).find('[name="name"]').val();
var productPrice = $(this).find('[name="price"]').val();
$.ajax({
url:'/api/ajaxrest/post' ,
method: 'POST',
processData: false,
contentType:"application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
id: productId,
name: productName,
price : productPrice
}),
complete: function(result){
console.debug(result)
$('#result3').text(result);
}
})
}
form
<h2>Add a new task</h2>
<form
class="datatable__row datatable__row--add"
method="POST"
action="http://localhost:8080/v1/task/createTask"
data-product-add-form=""
>
<fieldset class="datatable__row-section datatable__row-section--input-section">
<label class="datatable__input-label">
Product Id
</label>
<input type="text" name="id" placeholder="Insert a task name" th:required="required" />
</fieldset>
<fieldset class="datatable__row-section datatable__row-section--input-section">
<label class="datatable__input-label">
Task name
</label>
<input type="text" name="name" placeholder="Insert a task name" th:required="required" />
</fieldset>
<fieldset class="datatable__row-section datatable__row-section--input-section">
<label class="datatable__input-label">
Task content
</label>
<textarea name="price" placeholder="Insert task content" th:required="required"></textarea>
</fieldset>
<fieldset class="datatable__row-section datatable__row-section--button-section">
<button type="submit" data-task-add-button="" class="datatable__button">Add a task</button>
</fieldset>
</form>
<fieldset>
<span id="result3"></span>
</fieldset>
I do not know how to display this returned object. This function does not display me in the view of this object
$('#result3').text(object);
I tried:
$('#result3').text(object.name + object.price);
but displayed nothnig. so I checked this object using consol.debuger and here is a screenshot
There is no name nor price on that object. It says so on your screen-shot. There is however responseJSON, with name and price. So why not use those? (I also added space between the two, but you should format those as you like/need)
$('#result3').text(object.responseJSON.name + " " + object.responseJSON.price);