I am using a form to collect data. In the form consists a part where a tbody is present and is empty at the beginning. Using few functions, one can fill this tbody with the data from an array. The array is accessed in the js file. After completing all the aspects of the form, most of the data from the form is sent to the post request in my routes file of index.js
. Most of the data items are accessed by their name
attribute such as req.body.nameOfInputField
.
How am I supposed to send the array in the req.body or access it?
main.hbs
<form autocomplete="off" action="/post-prop" method="post" onsubmit="return validateForm()" id="post-prop-form" enctype="multipart/form-data" class="col-lg-12">
<div class="row">
..
<table id="tableId">
..
<tbody id="bodyId">
</tbody>
..
</table>
..
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
main.js
let arr = [];
$(function(){
...
//Various functions called such as add, edit, delete are used for 'arr'
//These changes seen in tbody
}
function validateForm(){
//This function is called onsubmit of form
// What should be placed here or anywhere else
// so I can send my 'arr' to POST route in index.js
}
index.js
router.post('/post-prop', isLoggedIn, upload.single('image'), function(req, res, next){
const data = new Data({
data1 : req.body.data1,
data2 : req.body.data2,
array : //What should be placed here for 'arr'
});
});
I tried surfing the net however could not find anything that related to my issue.
Update
I am not using any AJAX function call. It is a simple post request sent from my form. The 'Data' model present in my index.js
allows me to add values to attributes of the model hence I can only define data
after it has been sent.
As per the answer suggested by @sigfried I added the following code in the respective files
main.js
function validateForm(){
....
const data = {
fields: arr
};
jQuery.ajax({
data: JSON.stringify(data),
content: 'application/json'
});
...
}
index.js
router.post('/post-prop', isLoggedIn, upload.single('propImage'), function(req, res, next){
console.log(req.body.fields); //However this comes as undefined
...
}
I hope I haven't been ignorant of implementing it in the wrong way.