Add object(s) to form submission (post) - javascript

I have a form and I have two objects I want to submit with that form.
<form role="form" id="orderform" action="test.php" method="post">
<input type="text" name="test">
<button type="submit">Place Order</button>
</form>
<script>
var items1 = {name: "test", value: "123"} //needs to submit with form
var items2 = {name: "test2", value: "456"} //meeds to submit with form
$("#orderform").submit(function(event) {
event.preventDefault();
//do something to add items1 and items2 to form.
}
</script>
How do I submit items1 and items2 with the form submission?

There are already answers to this question (Adding POST parameters before submit) but I personally think that adding dom elements should not be the way to go.
My approach would be to get the form data onsubmit and add your objects to it. Afterwards send the request. The major benefits are you can make use of ajax (which in fact improves the user experience) and dont have to modify / add dom elements which can get quite nasty if you add more than 2 objects.
var items1 = {
name: "test1",
value: "123"
} //needs to submit with form
var items2 = {
name: "test2",
value: "456"
} //meeds to submit with form
$("#orderform").submit(function(event) {
event.preventDefault();
//add the items to the form data
let data = $(this).serializeArray();
data.push(items1);
data.push(items2);
let params = $.param(data);
//send the data with ajax
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: data,
success: function(data) {
window.location.href = "success.php"+params;
},
error: function() {
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" id="orderform" action="test.php" method="post">
<input type="text" name="test">
<button type="submit">Place Order</button>
</form>
In order to show the results on a seperate page I'd add the form data as get parameters to the success redirect and show them like this.
Please also read on XSS and how to avoid it (sanitize input / parameters).
success.php should look like the following.
echo $_GET["test1"];
echo $_GET["test2"];

You can add them as hidden inputs.
let items = [
{
name: 'bar',
value: 'foo',
},
{
name: 'qux',
value: 'baz',
},
];
let form = document.getElementById('orderform');
let itemsToBeSubmited = items;
itemsToBeSubmited.forEach((item) => {
let input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', item.name);
input.setAttribute('value', item.value);
form.appendChild(input);
});
<form role="form" id="orderform" action="test.php" method="post">
<input type="text" name="test">
<button type="submit">Place Order</button>
</form>

Related

Unable to redirect to homepage after posting a form - Express,EJS and JS

I have a view which contains a form and looks like this,
<form class="flex-form" id="form" method="">
<div class="form-component">
<label>Type</label>
<input type="text" id="type" name="type">
</div>
<div class="form-component">
<div class="form-component"><label><b>Contents</b></label></div>
<label>Savoury</label><input type="text" name="savoury" id="savoury">
<label>Fillings</label><input type="text" name="fillings" id="fillings">
<label>Amount</label><input type="text" name="amount" id="amount">
<div class="flex-component">
<button class="set-button" type="button" id="set">Set Item</button>
</div>
</div>
<div class="form-component">
<label class="description-label">Description</label>
<textarea class="fixed-textarea" id="description" name="description" cols="15" rows="10"></textarea>
</div>
<div class="form-component">
<label >Unit Price</label>
<input type="text" id="price" name="unit_price">
</div>
<div class="flex-component">
<button class="form-button" type="submit">Add</button>
</div>
</form>
I have a JavaScript that allows me to capture some intermediary information (via the Set Item button) from the form before the form gets submitted (via the Add Button). I want to handle the form's submission from the script since I need to capture the intermediary data.
let collectedItems = [];
let setter = document.getElementById('set');
let form = document.getElementById('form');
setter.addEventListener('click',getSetContent);
function getSetContent() {
let type = document.getElementById('savoury');
let fillings = document.getElementById('fillings');
let amount = document.getElementById('amount');
const content = {
type: type.value,
fillings: fillings.value.split(','),
amount: Number(amount.value)
};
collectedItems.push(content);
clearInputFields([type,fillings,amount]);
}
function clearInputFields(inputFields) {
inputFields.forEach(field => {
field.value = ''
});
console.log(collectedItems);
}
form.addEventListener('submit',submitForm);
function submitForm() {
const type = document.getElementById('type').value;
const desc = document.getElementById('description').value;
const price = Number(document.getElementById('price').value);
const content = collectedItems;
const data = {
type: type,
contents: content,
description: desc,
unit_price: price
};
post('http://localhost:8001/add/box',
{ 'Content-Type': 'application/json' },
JSON.stringify(data)
);
}
function post(endpoint,header,body) {
const response = fetch(endpoint,{ method: 'POST',headers: header,body: body });
response.then(
resp => {
if (resp.ok) {
console.log('form submitted');
} else {
console.log('form not submitted');
}
}
)
}
I then make a POST request using fetch() to an endpoint I have setup in Express which looks like this,
app.post('/add/box',(req,res) => {
const box: any = req.body;
console.log(box);
// DO SOME DB STUFF
res.redirect('/');
});
The form submission works as intended (logs to terminal using nodemon), however I am unable to redirect to the homepage. Instead I stay on the form page after the submission has occurred and I can't figure out why. Any help with this issue is much appreciated.

Form data not saved in localstorage except I refresh the browser

I am working on a form. The aim is to save the form data to localStorage, and also populate the form fields with the data in the localStorage.
After submitting the form, data do not save to localStorage except I refresh the browser.
Even after I refresh and I see the data in localStorage, I open a new browser, launch the form. I check the localStorage but, the data do not show.
I will appreciate your advice.
Thank you
After submitting the form
After reloading the page
HTML Code
<form action="https://formspree.io/f/xwkaygyj" method="POST">
<div class="name">
<input id="name" type="text" name="name" required placeholder="Name" oninput="onChangeHandler(this)"/>
<input id="email" type="email" name="email" required placeholder="example#gmail.com" oninput="onChangeHandler(this)"/>
<textarea id="message" name="message" cols="30" rows="7" maxlength="500" placeholder="Write your message here" required oninput="onChangeHandler(this)">
</textarea>
<button type="submit">Send</button>
</div>
</form>
Javascript Code
const formName = document.getElementById('name');
const email = document.getElementById('email');
const message = document.getElementById('message');
let formData = { name: '', email: '', message: '' };
const onChangeHandler = (event) => {
switch (event.name) {
case 'name':
formData = { ...formData, name: event.value };
break;
case 'email':
formData = { ...formData, email: event.value };
break;
case 'message':
formData = { ...formData, message: event.value };
break;
default:
break;
}
localStorage.setItem('data', JSON.stringify(formData));
};
const reloadBrowser = JSON.parse(localStorage.getItem('data'));
if (reloadBrowser) {
formName.value = reloadBrowser.name;
email.value = reloadBrowser.email;
message.value = reloadBrowser.message;
}
I believe you can use AJAX to efficiently submit your request to server, this is cleaner and less error-prone rather than manually capturing input data through swtich statement, furthermore you ascertain the data is successfully submitted to server and a copy is stored in local storage as well.
$.ajax({
type: 'POST',
url: $("form").attr("action"),
data: $("form").serialize(),
//Or your custom data
success: function(response) {
localStorage.setItem('data', JSON.stringify(formData));
},
});

Storing HTML form input in a JS object

I know there is a very similar question asked over here but my object hierarchy is different than the one in that question.
Anyways, I want to store the HTML form input data in to my JavaScript object. Here is my HTML form code:
<form id="newAuction">
<input id="title" name="title" required type="text" value="" />
<input id="edate" name="edate" required type="datetime" value="" />
<input id="minbid" name="minbid" required type="number" value="" />
<button class="btn btn-primary">Submit</button>
</form>
What I want is to get the values of these 3 inputs and store it in my JS object.
I know the proper JSON format needed to post the data to my API. (I tried POSTing with POSTman and I get a status 200, so it works). The proper format is:
{
"auction": {
"Title": "Auction1",
"EDate": "01/01/1990",
"MinBid": 30
},
"productIds": [1,2,3]
}
This is what my JS object looks like:
<script>
$(document).ready(function() {
var vm = {
auction: {},
productIds: []
};
//validation and posting to api
var validator = $("#newAuction").validate({
//assigning values
vm.auction.Title = document.getElementById('title').value;
vm.auction.MinBid = document.getElementById('minbid').value;
vm.auction.EDate = document.getElementById('edate').value;
vm.productIds.push(1);
submitHandler: function () {
$.ajax({
url: "/api/newAuction",
method: "post",
data: vm
})
.done(function () {
toastr.success("Auction Added to the db");
//setting the vm to a new vm to get rid of the old values
var vm = { auction: {}, productIds: [] };
validator.resetForm();
})
.fail(function () {
toastr.error("something wrong");
});
return false;
}
});
});
</script>
As you can see, I am using document.getElementById('title').value; to get the values and assign them but I'm getting the syntax error Expected : Comma expected
Not sure if this matters, but this is inside a .NET MVC5 project.
Move your value assignment set of codes inside submitHandler. Check the syntax of validate() https://jqueryvalidation.org/validate/
//validation and posting to api
var validator = $("#newAuction").validate({
submitHandler: function () {
//assigning values
vm.auction.Title = document.getElementById('title').value;
vm.auction.MinBid = document.getElementById('minbid').value;
vm.auction.EDate = document.getElementById('edate').value;
vm.productIds.push(1);
$.ajax({
url: "/api/newAuction",
method: "post",
data: vm
})
.done(function () {
toastr.success("Auction Added to the db");
//setting the vm to a new vm to get rid of the old values
var vm = { auction: {}, productIds: [] };
validator.resetForm();
})
.fail(function () {
toastr.error("something wrong");
});
return false;
}
});

jQuery: intercept form submit and build data

I have a form with some custom values and I want to intercept it's submission and build myself the data that is passed to the backend.
I've searched and I can intercep the submit by doing:
$("#search-form").submit(function(e){
e.preventDefault();
var form = this;
form.submit();
});
Before manually submitting, I want to build the data passed to the backend. For example, I would like to build the following data:
{
search: {
someField1: "someValue1",
someField2: "someValue2",
someFields: [
{
nestedField1: "value1",
},
{
nestedField2: "value2"
}
]
}
}
To be clear, the original data from the form I want to completely remove, I don't care what's in it.
You could intercept the form submit , cancel it and just use a ajax call to send over whatever you like.
var data = {
search: {
someField1: "someValue1",
someField2: "someValue2",
someFields: [{
nestedField1: "value1",
},
{
nestedField2: "value2"
}
]
}
};
$('#test').submit(function(e) {
e.preventDefault();
e.stopPropagation();
$.post(this.action, data);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="test" action="http://google.com" method="POST">
<input type="text" />
<input type="submit" />
</form>

Vue.js lib that setAttributes('value', data) on an v-model input

I have a JS library that encrypts form data. When submitting the form, it searches for the input with id "adyen_library_data" and sets its attribute 'value' of the encrypted data.
Here's my HTML (inside the #wrapper element) :
<form class="ui form" id="adyen-encrypted-form" onsubmit="return false;">
<input type="hidden" id="adyen_encrypted_data" v-model="input.payment.card.adyen_encrypted_data"/>
<button type="submit">Submit</button>
</form>
I have other fields like card number, CVC, holdername, etc.
My Vue.js script:
var vm = new Vue({
el: "#wrapper",
data: {
input: {
payment: {
card: {
adyen_encrypted_data: '',
}
}
}
});
When the form gets submitted, the "adyen_encrypted_data" changes
before :
after :
But no way, when I check for vm.input.payment.card.adyen_encrypted_data it's empty ! Why ?
Why Vue.js is not responding to element.setAttribute('value', data) ? How can I get the value ?

Categories

Resources