HTML5 FormData sending empty objects via JQuery - javascript

I have a basic script that is as follows:
$(".submit").click(function(){
var fd = new FormData();
fd.append('username', 'Bob');
$.ajax({
url: '/signup',
type: 'post',
data: fd,
processData: false,
contentType: false,
success: function (data) {
console.log("Success: ", data);
}
});
});
When the request hits my server, I receive a req.body of {} (empty) and there is nothing in req that points to data being sent. Whats going on here? How can I send data with FormData?
I wanted to test getting basic preset data from FormData and was unsuccessful. The values console logged in Chrome show an empty formData object, with only its constructor and the available 'append' method.
I am using jQuery v 2.1.4 and HTML5 and have confirmed that window.FormData is a valid object in Google Chrome.
My goal is to have a form that a user can enter an email, password, avatar, and a profile background image with the following form:
<form id="msform" enctype="multipart/form-data" name="msform">
<!-- Progress Bar -->
<ul id="progressbar">
<li class="active">Basic Information</li>
<li>Profile Customization</li>
</ul>
<!-- Step One -->
<fieldset>
<h2 class="title">Basic Information</h2>
<input type="text" name="username" placeholder="Username" />
<input type="text" name="password" placeholder="Password" />
Avatar Image <input type='file' id='avatarImage' accept="image/*" name='avatarImage'>
<input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<!-- Step Two -->
<fieldset>
<h2 class="title">Profile Customization</h2>
<select id="dropdown" name="profileColor">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
Background Photo <input type='file' id='bgPhoto' accept="image/*" name='bgPhoto'> </div>
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="submit" name="submit" class="submit action-button" value="Submit" />
</fieldset>
</form>
Whats going on with FormData, it seems like a valid object, but I'm unable to append anything to it. I've looked, and it appears that others have seen an empty object in their console, but the data 'automagically(?)' appears on their server? My first code block is basically a copy for the docs and I'm having trouble with it. Would and CORS issues or CDN errors be the case? Something maybe not able to access as it should? No errors print in the log, only a blank object on my post request.
Thanks for the help!

If you are using Express as the backend, body-parser does not handle multipart/form-data, and you are referred to using multiparty instead. You can integrate Express with multiparty like so :
var express = require('express');
var multiparty = require('multiparty');
var app = express();
var data = new multiparty.Form();
app.post('/signup', function(req, res) {
data.parse(req, function(err, fields, files) {
if(err) throw err;
Object.keys(fields).forEach(function(name) {
console.log('got field named : ' + name + ', value : ' + fields[name]);
});
Object.keys(files).forEach(function(name) {
console.log('got file named : ' + name);
});
});
});
Do include event.preventDefault() in your click event handler
$(".submit").click(function(e){
e.preventDefault();
var fd = new FormData();
fd.append('username', 'Bob');
...
});

You aren't preventing the default form submit event and neither are you catching a submit by keyboard if user hits enter.
Try:
$("#msform").submit(function(e){
e.preventDefault();
var fd = new FormData();
fd.append('username', 'Bob');
$.ajax({
url: '/signup',
type: 'post',
data: fd,
processData: false,
contentType: false,
success: function (data) {
console.log("Success: ", data);
}
});
});
If you aren't sending files I would suggest using the simpler approach of removing the processData and contentType options and using $(this).serialize() for the data value

Related

I want to get my textbox values from HTML document and post those when submit button is pressed using Json file in node JS

This is my JS file:-
$(document).ready(function(){
$('form').on('submit', function(){
var email = $("form input[type=text][name=emails]").val();
var todo = {email: email.val(),
pass:dat.val()};
$.ajax({
type: 'POST',
url: '/project',
data: todo,
success: function(data){
//do something with the data via front-end framework
location.reload();
}
});
return false;
});
});
This is my html document:-
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="/assests/todo-list.js"></script>
<body>
<form>
<div class="container">
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="emails" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</head>
</html>
I want that when i click submit button value from both text boxes gets saved in my database(using Mlab),for that i am using a json file to fire post request to the server.
My main post request handler:-
app.post('/project',parser,function(req,res)
{
var register=Todo(req.body).save(function(err,data)
{
if(err) throw err
res.json(data);
});
});
EDIT:-
I removed my Javascript file and now i am directly posting the form using and i am able to save my email address but not the password.
This is my main code now :-
app.post('/views/register',parser,function(req,res)
{
var data={
email:req.body.emails,
password:req.body.passcode
};
var send=Todo(data).save(function(err)
{
if(err) throw err
res.render('login')
})
});
If I understand your question right, you're missing the contentType param.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
...
then try again.
I was not following the correct schema for the database when creating the object
var data={
email:req.body.emails,
password:req.body.passcode
};
The property name was pass and i was using password that's why it was not inserting the password.
var data={
email:req.body.emails,
pass:req.body.passcode
};

How to send image file from local machine to server using jquery ajax request

I have an html form with input type = file, I have a link to API to store images to cloud. In this feature, a user can upload a file from his local machine and upload it to the server. The server returns the cloud url of the uploaded image. In postman it is working fine, but when using with jquery I am not able to figure out how to accomplish this. In postman There are several parameters set like filename, tag and employeeID. In file name field there is choose file button and form-data radio button is checked.
This is my jquery code so far
$("#test-btn").on("click", function() {
$.ajax({
url: 'myURL/external/upload',
type: 'POST',
headers: {
"appID": "some value",
"version": "some value",
"empID": "some value",
"contentType": "application/x-www-form-urlencoded"
},
data: new FormData($("#test-form")),
processData: false,
contentType: false,
success: function() {
console.log(data)
},
error: function(e) {
console.log(e)
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form enctype="multipart/form-data" method="post" name="upload-image" id="test-form">
<input type="file" name="filename" />
<input type="text" name="tag" value="some value" />
<input type="text" name="empID" value="some value" />
</form>
<button id="test-btn">make</button>
I've replaced the confidential fields with dummy values.
$("form#test-form").submit(function(){
var formData = new FormData(this);
$.ajax({
url : 'myURL/external/upload',
type : 'POST',
data: formData,
async: false,
// your other config, params
success : function(){console.log(data)},
error : function(e){console.log(e)}
});
return false;
});
or you can try:
<form enctype="multipart/form-data" method="post" name="upload-image" id="test-form" action="myURL/external/upload">
<input type="file" name="filename" />
<input type="text" name="tag" value="some value" />
<input type="text" name="empID" value="some value" />
</form>
<button id="test-btn">make</button>
$("form#test-form").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function() {
// success
});
return false;
});

Getting an Ajax error "xxx" is not defined

I have looked through the numerous Stackoverflow questions, various tutorials and youtube vids and so far none (that I have found) address this issue for me...
I have a form to load a single file. It submits this fine without ajax.
<form asp-action="FileIndexView"
asp-controller="SuburbsAndPostcodesAdmin"
method="post"
enctype="multipart/form-data">
<div class="form-horizontal">
<div class="form-group">
<label class="col-md-4 control-label">Select the Suburbs and Postcodes latest CSV File:</label>
<input type="file"
name="CSVFile"
id="txtFileUpload"
class="col-md-8 control-label" />
</div>
<div class="form-group">
<input type="submit"
name="Submit"
value="Submit"
class="col-md-1 btn btn-primary"
disabled="disabled"
id="SubmitFile" />
</div>
</div>
I have an Ajax POST method. its called when you click the submit button. All good.
Here is the code.
$('#SubmitFile').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
//var fileUpload = input.files[0];
var url = "/SuburbsAndPostcodesAdmin/test";
var connId = $.connection.hub.id;
var fd = new FormData();
fd.append('File', input.files[0]);
fd.append('connId', connId);
$.ajax({
type: "POST",
url: url,
data: fd,
processData: false,
contentType: false,
});
When I step through this it errors on the:
"fd.append('File', input.files[0]);"
line with the following error in the console.
ReferenceError: input is not defined
<anonymous>
FileIndexView:127
n.event.dispatch()
jquery.min.js:3
n.event.add/r.handle()
jquery.min.js:3
EventLoop.prototype.enter()
...
Why is this erroring on this line?
How should it read so it is defined?
What should the file name be and why? (does this need to address back to the form)
The problem is with input.files[0] because here input is undefined.
Instead of
fd.append('File', input.files[0]); //here input is not defined
Try
fd.append('File', $("#txtFileUpload")[0].files[0]);
This "Formdata" object seems suspect. jQuery likes simple objects, i.e.
$.ajax({
type: "POST",
url: url,
data: {input: "A", somethingelse: 2, somethingmore: true},
processData: false,
contentType: false,
});
In your browser, use the developer options and go to the Network tab to see exactly what's being pushed to the server in the POST operation. I'll bet it doesn't fit what your server method is expecting, hence the exception.
EDIT
Didn't notice until now that you're trying to do file upload. It is well-documented as a pain-in-the-butt via AJAX. I've had success with a plug-in called DropZone. http://www.dropzonejs.com/

Sending Form Data to Node Server

I am trying to send some form data to an endpoint.
Here's my client side code:
<form name="form" action="http://localhost:8080/geodata" method="post">
<label for="minlat"> MinLat: </label>
<input type="text" name="MinLat" value="0"><br>
<label for="maxlat"> MaxLat: </label>
<input type="text" name="MaxLat" value="1"><br>
<label for="minlong"> MinLong: </label>
<input type="text" name="MinLong" value="0"><br>
<label for="maxlong"> MaxLong: </label>
<input type="text" name="MaxLong" value="1"><br>
<button type="submit" class="btn btn-success"> Submit <span class="fa fa-arrow-right"></span></button>
</form>
<script>
$(document).ready(function() {
$("#form")
.submit(function(event) {
var formData = {
'minLat' : $('input[name=MinLat]').val(),
'maxLat' : $('input[name=MaxLat]').val(),
'minLong' : $('input[name=MinLong]').val(),
'maxLong' : $('input[name=MaxLong]').val()
};
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
dataType: 'json',
processData: false,
type: 'POST',
}).done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
I have an enpoint on the server side code (express.js):
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.post("/geodata", function(req, res) {
console.log(req.body);
res.send("hi");
});
I wish to send this form data to the endpoint /geodata, and use that data to send a result back to the client side. First of all, when I hit submit, I get an empty {} in my terminal (which is the server side request.body). I was expecting form values in this request.body but don't receive them. How do I make sure my form values are being sent?
Secondly, res.send("hi") re-directs my initial page to a new page and prints "hi" there. Since I had made an ajax call, shouldn't the response just be logged and the webpage stays on the initial page?
Change the form action to '/geodata'(the endpoint)
also you dont need to make a ajax request as HTML5 forms will perform the request itself if a tag() is pressed/clicked.
after you click summit your page will become what ever response that is sent back from '/geodata' route
and req.body will return a object that represents the form data
dataType: 'json' means you are expecting json data from the server. remove dataType, and add this
data : JSON.stringify(formData),
contentType: 'application/json',
contentType would be the type of data you are sending to the server.

Using multer to recieve a FormData object as a node.js server

I have an HTML form with two buttons (along with other text input areas), and I have some front end javascript code to handle the submit. On the submit, I create a FormData object and store the file in it. Then I send that through an jquery ajax request to a node.js server. However, this is where the problem is - when I try to access the file in the server, the file is always undefined - i've tried accessing it with req.body, req.files, req.file but its always undefined. Is this a problem with the ajax request, or the way i'm receiving it?
upload file button:
<input id="element_3" name="element_3" class="element file required" accept="application/pdf" type="file"/>
submit button:
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit"/>
handle submit:
$('#form_1039889').submit(function(event) {
event.preventDefault();
event.stopImmediatePropagation();
var file = $('#element_3').get(0).files[0];
var fd = new FormData();
fd.append('pdf', file);
$.ajax({
url: '/addPdf',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(response) {
//success TODO code
}
});
});
relevant server code:
app.post('/addPdf', [multer({dest: "./uploads/"}).single('avatar'), function(req, res) {
console.log("file: " + req.file);
}]);
Instead of single('avatar') use single('pdf.file') because you set pdf object for file.
Name that we pass inside Single should match with form-data key. So Change .single('avatar') with .single('pdf').
So your node js code will look like this:
app.post('/addPdf', [multer({dest: "./uploads/"}).single('pdf'), function(req, res) {
console.log("file: " + req.file);
}]);

Categories

Resources