Merging form and fieldset doesn't work? - javascript

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.

Related

JQuery Ajax Form Submit with Form Data returns nothing on submit

The following example below returns nothing. Could you please clarify if I missed something?
Javascript:
$('#add-modal').submit(function(e) {
e.preventDefault();
var formData = new FormData( document.getElementById("add-modal"));
$.ajax({
type: "POST",
url: "/add-form",
data: formData,
processData: false,
contentType: false,
success: function (data) { console.log("SUCCESS : ", data); },
error: function (e) {console.log("ERROR : ", e); }
});
});
HTML (submission form):
<form id="add-modal" method="POST" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" required>
</div>
<div class="form-group">
<label>Classes</label>
<select class="form-control" name="classes">
<option value="Direct">Direct</option>
<option value="Merketing">Merketing</option>
<option value="Partnets">Partnets</option>
</select>
</div>
<div class="form-group">
<label>File</label>
<input type="file" class="form-control" name="file">
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Add">
</div>
</form>
Server-side (node js):
app.post('/add-form', function(req, res, next){
console.log(req.body);
});
With my best regards,
Evgeniy
The form is using express to process the back-end. The form is multi-part and processing a file upload.
A multi-part processor is required to parse the form data. The comment by #ChrisG suggested using multer. It was expected that bodyParser was doing this parsing. Replacing it with multer which needs to be imported in the express app as per the multer documentation
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
app.post('/add-form', function(req, res, next){
console.log(req.body);
});

Fetch in forEach Javascript to send data in MongoDB

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?

Node.js Sails html data using "POST" method can not pass to controller

I am new to MVC.
When I want to pass the form data from ejs file to controller, it does not work.
Create.ejs file
<!--create.ejs-->
<h2 class="col-sm-offset-1">Person Create form</h2>
<form action="/person/create" method="POST" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2">Name: </label>
<div class="col-sm-8">
<input class="form-control" name="Person[name]" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Age: </label>
<div class="col-sm-8">
<input class="form-control" name="Person[age]" type="number"
min="0" max="120">
</div>
</div>
<button class="btn btn-default col-sm-offset-2" type="submit" value="ADD">Submit</button>
PersonController.js
module.exports = {
create: function(req, res) {
if (req.method == "POST") {
Person.create(req.body.Person).exec( function(err, model) {
return res.send("Successfully Created!");
});
} else {
return res.view('person/create');
}
},
The result is that it cant get inside the (req.method == "POST") condition.
Give me 404 error.
A 404 is a not found result.
When POSTing ensure you are targeting your Controller functions try:
'POST /person/create': 'person/PersonController.create',
Though why do you have a subfolder named person when you are using a controller?
Using Actions
In Sails v1.0 you would separate your controller functions into more manageable actions. A sub folder api/controllers/person makes more sense now.
Your routes.js file would read 'POST /person/create': {action: 'person/create'},
For simplicity I have removed req.body.Person as an array...
<form action="/person/create" method="POST" class="form-horizontal">
<input type="hidden" name="_csrf" value="<%= _csrf %>" />
<div class="form-group">
<label class="control-label col-sm-2">Full Name: </label>
<div class="col-sm-8">
<input class="form-control" name="fullName" placeholder="John Johnson" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Age: </label>
<div class="col-sm-8">
<input class="form-control" name="age" type="number" min="0" max="120">
</div>
</div>
<button class="btn btn-default col-sm-offset-2" type="submit" value="ADD">Submit</button>
</form>
then your async function would be like...
module.exports = {
friendlyName: 'Create Person.',
description: 'Creating a new person.',
exits: {
success: {
description: 'Person Created successfully.',
viewTemplatePath: 'person/review',
}
},
fn: async function (inputs, exits) {
if (!this.req.me) throw {redirect: '/'};
let params = this.req.allParams();
let person = await Person.create(params).fetch();
return exits.success({person:person});
}
}
Like #Tejashwi suggested you need to change your route to a POST.
'POST /api/v1/create': { action: 'create/person-create-form' },

Jquery Not Sending the Form to HTTP

I'm having some problems with Jquery/Ajax.
This is my code for the form :
<form class="form-auth-small" method="POST" id="form" enctype="multipart/form-data">
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Email</label>
<input type="email" class="form-control" name="email" value="samuel.gold#domain.com" placeholder="Email">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Name</label>
<input type="text" class="form-control" name="name" value="John">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only">Phone</label>
<input type="text" class="form-control" name="phone" placeholder="938434928">
</div>
<div class="form-group">
<label for="signin-email" class="control-label sr-only"></label>
<input type="password" class="form-control" name="password" placeholder="****">
</div>
<div class="form-group">
<input name="image" type="file" />
</div>
<button type="submit" id="submit" class="btn btn-primary btn-lg btn-block">Register</button>
</form>
And this is my code to AJAX/Jquery:
<script>
$(".submit").on("click", function(e) {
var form = $("#form");
// you can't pass Jquery form it has to be javascript form object var formData = new FormData(form[0]);
console.log(formData);
$.ajax({
type: "POST",
url: '/user/signup/',
data: formData,
contentType: false, //this is requireded please see answers above processData: false, //this is requireded please see answers above //cache: false, //not sure but works for me without this error: function (err) { console.log(err);
success: function(res) {
console.log(res);
},
});
});
</script>
When i do console.log to check that from form i don't receive any value, and when i check in network i dont see any HTTP callback.
Your code doesn't work because you were using the class selector token . (dot) instead of the id selector token # hashtag. Further details can be found on the documentation
Change this instruction
$(".submit").on("click", function(e) // …
to
$("#submit").on("click", function(e) // …
You dont have submit class. You have id="submit"
$("#submit").on("click", function(e) {
Use this and it should work.
Also change type="submit" to type="button" or in your js code you need to add
e.preventDefault();

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.

Categories

Resources