Fetch in forEach Javascript to send data in MongoDB - javascript

I want to use Fetch to send data in my mongoDB.
I would like to read an excel file and then submit each entry in a form.
This is my code:
<form method="post" action="/content" id="importcontent">
<label for="name" class="col-md-3 label-control">Import XLSX file:</label>
<input type="file" name="file" class="form-control" id="file">
<div style="display: none;">
<input type="text" name="title" class="form-control" id="titre">
</div>
<input type="submit">
</form>
<script src="https://unpkg.com/read-excel-file#4.x/bundle/read-excel-file.min.js"></script>
<script>
let importcontent=document.getElementById("importcontent");
let titre=document.getElementById("titre");
const input = document.getElementById('file');
importcontent.addEventListener('submit', (event)=>{
event.preventDefault();
readXlsxFile(input.files[0]).then((rows) => {
input.remove();
rows.forEach((row)=>{
titre.value=row[0];
fd= new FormData(importcontent);
fetch('/content',{
method:'POST',
body: fd
}).then(checkStatus)
.catch((error)=>{
console.error('request failed', error);
})
});
}
});
});
function checkStatus(response) {
if (response.status >=200 && response.status <300){
console.log("Ok");
}
}
It isn't working, I have an error 500.
Can you help me please?

Related

AXIOS POST form submit to WordPress returning 200 with data returning 0

I have a contact form which I am trying to POST the data via AXIOS using formData to send email via WP_mail.
Submitting the form seems to be working in the sense of:
The page isn't refreshing/adding parameters to the url
Using for (var value of formData.values()) {console.log(value);} to check what values are being grabbed by formData, console.log shows the different input values
response.status is showing 200
The problems start with response.data returning 0 rather than the data from the form that is being submitted.
This is my form
<form class="js-process dark-form">
<fieldset>
<label for="name">First name*</label>
<input type="text" name="name" placeholder="Enter your first name" />
<label for="last-name">Last name*</label>
<input type="text" name="last-name" placeholder="Enter your last name" />
<label for="email-address">Email address*</label>
<input type="email" name="email-address" placeholder="Enter your email address" />
<label for="telephone">Telephone*</label>
<input type="tel" name="telephone" placeholder="Enter your phone number" />
</fieldset>
<fieldset>
<label for="enquiry-form">Nature of enquiry*</label>
<!-- TEMP -->
<select id="enquiry-form" name="enquiry-form" data-label-value="test">
<option disabled value="">test</option>
<option value="test">test</option>
<option value="test">test</option>
<option value="test">test</option>
</select>
<label for="your-message">Your message*</label>
<textarea name="your-message" placeholder="Please tell us your message"></textarea>
</fieldset>
<input type="submit" value="Submit">
</form>
This is my JS to POST the form data
import axios from 'axios';
const processForm = (e) => {
const form = e.target;
e.preventDefault();
// let formData = new FormData(form);
const formData = new FormData();
// Console.log all formData values for testing
for (var value of formData.values()) { console.log(value); }
formData.append('action', 'contact_form');
formData.append('first_name', 'my first name');
axios({
method: 'POST',
url: WP.ajax,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: formData,
})
.then(function (response) {
console.log(response);
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
},
(error) => {
console.log(error);
});
return false;
};
const initProcessForm = () => {
const forms = document.querySelectorAll('.js-process');
forms.forEach(form => {
form.addEventListener('submit', processForm);
});
};
export default initProcessForm;
I'm not sure what I am missing here to get the data from the form to POST correctly. I know i've not even got round to the WP_mail side of things! I am new to using AXIOS so if anyone can point me in the right direction with this code or has a better way of doing this i'd be grateful to know : )
Thanks in advance.

upload image using vue js with form text fields

I started working on small project using Vue Js and I would like to add an upload file option in my contact form, I use serialize for the form because I have a lot of input text fields. but it doesn't work with append function. How can I add upload file to my serialized form
This is my code :
addProducts () {
const formData = $('#add-product').serialize()
// formData.append('image', this.selectedFile, this.selectedFile.name)
this.$axios.$post('http://endpoint.quicknsales.com/api/Product', formData).then((response) => {
this.validation(response)
if (response.success) { this.refresh = true }
})
}
A part of my HTML code :
<div class="form-group mb-2">
<div class="row">
<div class="col-md-6">
<label class="mb-0"><strong>Buying Price:</strong></label>
<input
id="product_buying_price"
v-model="formFields.product_buying_price"
type="text"
class="form-control rounded-0"
placeholder="Product Buying Price"
name="general[product_buying_price]"
>
</div>
<div class="col-md-6">
<label class="mb-0"><strong>Selling Price:</strong></label>
<input
id="product_selling_price"
v-model="formFields.product_selling_price"
type="text"
class="form-control rounded-0"
placeholder="Product Selling Price"
name="general[product_selling_price]"
>
<input id="file" type="file" name="general[file]">
</div>
</div>
</div>
How can I add the upload file to my form, as you can see I have already used append function but it doesn't work
after two days this is my solution :
const formData = new FormData()
formData.append('image', this.selectedFile, this.selectedFile.name)
$($('form-in-question').serializeArray()).each(function (i, field) {
formData.append(field.name, field.value)
})
this.$axios.$post('endpoint.com', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then((response) => {
this.validation(response)
if (response.success) { this.refresh = true }
})

Upload input don't work when AJAX is invoked [duplicate]

I've a <form> to upload an image and a <fieldset> to send some data using AJAX, they both work fine, but my problem happens when I try to merge them in one form. I'm using Node.JS server.
Upload <form>:
<form method="post" enctype="multipart/form-data" action="upload">
<input type="file" name="upl"/>
<input type="submit" value="Send"/>
</form>
Node.JS router upload post:
router.post('/upload', upload, function (req, res, next) {
console.log(req.file);
res.status(204).end();
});
<fieldset>:
<div id="addAdv">
<fieldset class="form-group">
<label for="inputTimeStamp">Time</label>
<input id="inputTimeStamp" type="text" class="form-control"/><br/>
<label for="inputURL">URL</label>
<input id="inputURL" type="url"/><br/>
<button id="btnAddAdv" type="submit" class="btn btn-primary">Submit</button>
</fieldset>
</div>
Node.Js router data post:
router.post('/addadv', function(req, res) {
Feed.collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
AJAX:
$('#btnAddAdv').on('click', addAdv);
function addAdv(event) {
.....
$.ajax({
type: 'POST',
data: newUser,
url: '/addadv',
dataType: 'JSON'
}).done(function( response )...}
Let's try to merge them:
<div id="addAdv">
<form method="post" enctype="multipart/form-data" action="upload">
<fieldset class="form-group">
<input type="file" name="upl"/>
<label for="inputTimeStamp">Time</label>
<input id="inputTimeStamp" type="text" class="form-control"/><br/>
<label for="inputURL">URL</label>
<input id="inputURL" type="url"/><br/>
<input type="submit" id="btnAddAdv" value="Send"/>
</fieldset>
</form>
</div>
Also tried:
<button id="btnAddAdv" type="submit">Send</button>
If you're submitting your merged form via the submit button and not via XHR, then you need to add name attributes for your non-file fields, otherwise the browser will not send them to the server.

Merging form and fieldset doesn't work?

I've a <form> to upload an image and a <fieldset> to send some data using AJAX, they both work fine, but my problem happens when I try to merge them in one form. I'm using Node.JS server.
Upload <form>:
<form method="post" enctype="multipart/form-data" action="upload">
<input type="file" name="upl"/>
<input type="submit" value="Send"/>
</form>
Node.JS router upload post:
router.post('/upload', upload, function (req, res, next) {
console.log(req.file);
res.status(204).end();
});
<fieldset>:
<div id="addAdv">
<fieldset class="form-group">
<label for="inputTimeStamp">Time</label>
<input id="inputTimeStamp" type="text" class="form-control"/><br/>
<label for="inputURL">URL</label>
<input id="inputURL" type="url"/><br/>
<button id="btnAddAdv" type="submit" class="btn btn-primary">Submit</button>
</fieldset>
</div>
Node.Js router data post:
router.post('/addadv', function(req, res) {
Feed.collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
AJAX:
$('#btnAddAdv').on('click', addAdv);
function addAdv(event) {
.....
$.ajax({
type: 'POST',
data: newUser,
url: '/addadv',
dataType: 'JSON'
}).done(function( response )...}
Let's try to merge them:
<div id="addAdv">
<form method="post" enctype="multipart/form-data" action="upload">
<fieldset class="form-group">
<input type="file" name="upl"/>
<label for="inputTimeStamp">Time</label>
<input id="inputTimeStamp" type="text" class="form-control"/><br/>
<label for="inputURL">URL</label>
<input id="inputURL" type="url"/><br/>
<input type="submit" id="btnAddAdv" value="Send"/>
</fieldset>
</form>
</div>
Also tried:
<button id="btnAddAdv" type="submit">Send</button>
If you're submitting your merged form via the submit button and not via XHR, then you need to add name attributes for your non-file fields, otherwise the browser will not send them to the server.

AJAX does not respond to form submission

I wrote a toy program to learn AJAX, which is to submit the user registration form to web server, however, the program on the server side cannot receive the data. I guess the error is on the following JS code using jQuery:
$(document).ready(function() {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData, registerResults);
},
registerResults: function() {
console.log("register success!");
} // end of registerResults
}); // end of ready
The corresponding html form is as following:
<form class="form-horizontal" role="form" id='registerForm' method='POST' action="/admin/user/signup">
<div class="form-group">
<label class="col-sm-3 control-label" for="fullname">Fullname: </label>
<div class="col-sm-5">
<input class="form-control" type='text' id="fullname" name='fullname' placeholder="Full Name" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="username">Username: </label>
<div class="col-sm-5">
<input class="form-control" type='text' id="username" name='username' placeholder="Username" />
</div>
</div>
<div class="form-group">
<input type='submit' value="Submit" class="register-form-button" form='user-create-form' />
</div>
</form>
can someone help me with my JS code using jQuery? Thanks a lot!
Like Felix said, your JavaScript syntax is invalid. Open up the JS console and refresh the page, and you'll see syntax errors.
Here's a shot at fixing it:
$(document).ready(function () {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData)
.done(registerResults)
.fail(registerError);
});
function registerResults() {
console.log("register success!");
}
function registerError() {
console.log("There was an error");
}
});
The registerResults function was a namespace function based on the formatting, but you only need a standard function like the below.
$(document).ready(function () {
$('#registerForm').submit(function () {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData, registerResults);
});
function registerResults() {
console.log("register success!");
} // end of registerResults
}); // end of ready

Categories

Resources