Sending Form Data to Node Server - javascript

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.

Related

jquery ajax api post method error with nodejs and express server ... 405: unable to load resource

I am trying to login a new user and post that instance to SQL using express. On the front end I am getting a server 405 error with my jquery ajax post request.
jquery
the front end request to the backend
i am getting 405 server error
$("#form").on('submit', function(e){
e.preventDefault();
var user = {
email: $('loginemail').val(),
password: $('loginpassword').val()
};
$.ajax({
method: "POST",
url: "/signup",
data: user
}).then(function(res){
if(res.user){
console.log("boom");
window.location.href = "./profile-page/index.html";
}
});
express router
the controller file routed to the /signup post method
using express and sequelize
create : function(req,res){
User.create(req.body).then(function(result,error){
if(error){
console.log(error);
res.send(error);
}else{
res.send("./public/profile-page/index.html");
}
});
}
this is the html section of the code
<form id="form" >
<div class="container">
<h1>Sign Up</h1>
<label><b>Email</b></label>
<input id="loginemail" type="text" placeholder="Enter
Email"name="email" required>
<br>
<label><b>Password</b></label>
<input id="loginpassword" type="password" placeholder="Enter
Password" name="password" required>
<br>

Format of data received through ajax request?

I have client side code that looks like this:
<form name="sendCoordinates" action="http://localhost:8080/geodata" method="post">
<label> MinLat: </label>
<input type="text" name="MinLat" value="0"><br>
<label> MaxLat: </label>
<input type="text" name="MaxLat" value="1"><br>
<label> MinLong: </label>
<input type="text" name="MinLong" value="0"><br>
<label> MaxLong: </label>
<input type="text" name="MaxLong" value="1"><br>
<input type="submit" value="submit" id="s1">
</form>
<script>
$("#sendCoordinates")
.on('submit', function(e) {
e.preventDefault();
var $form = $(e.target),
formData = new FormData();
params = $form.serializeArray();
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(result) {
console.log(result + "you");
}
});
});
</script>
I am sending this form data to an endpoint /geodata.
app.post("/geodata", function(req, res) {
console.log(req.body);
});
My question is, under a successful post, what would console.log(req.body) print on the server side? I am unable to tell yet as my client is not sending any information yet due to some bug. This will help me write my server side code according to the data I receive in the post request.
Looks like you're using Express. In general practice, request bodies are parsed as JSON (see Express req.body docs), but it depends on the parsing middleware you're using (body-parser is the common one in Express apps).
It also depends on the Content-Type header of the request. From the Express docs I mentioned above, they give an example:
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
It looks like you currently set contentType: false in your AJAX request, so that will just send raw data to your server.
To answer your question more concretely
My question is, under a successful post, what would console.log(req.body) print on the server side?
It depends on the Content-Type and what middleware (if any) you are using the parse request bodies.

Multiple Submit Buttons - html express node js

I'm trying to do a like/dislike system. So essentially, there are two buttons on the html side.
<form method="post" name="ratings">
<input type="submit" name="vote" value="like">
<input type="submit" name="vote" value="dislike">
</form>
However, I only know how to do a single function. How can I seperate it? I'm working in node js.
So, like the first line of code looks like this:
router.post('/test/*', function (req, res) {
Like what would the if statement look like in javascript? or do I have to change the html code and do something with onclick? Any response would be appreciated.
I figured it out. You can get the name from req.body.vote and then use that value to do whatever.
var inputValue = req.body.vote;
if (inputValue == "like") {
...
I suggest you to use ajax, somelike this..
Buttons:
<button name="btnLike" value="like" onclick="like()">
<button name="btnDislike" value="dislike" onclick="dislike()">
JS:
function like(){
$.ajax({
url: "http://localhost:3000/like",
type: "POST",
data: {like: 'yes'}, //send this to server
success: function(returned) {
console.log(returnet); // here can get the return of route
},
error: function() {
}
});
}
function dislike(){
$.ajax({
url: "http://localhost:3000/dislike",
type: "POST",
data: {dislike: 'yes'}, //send this to server
success: function(returned) {
console.log(returnet); // here can get the return of route
},
error: function() {
}
});
}
Routes:
router.post('/like', function (req, res) {
}
router.post('/dislike', function (req, res) {
}
You can also use formaction
<button type="submit" formaction="/like" name="vote"></button>
<button type="submit" formaction="/dislike" name="vote"></button>
Below is the link
Parsing Form With Multiple Submits

HTML5 FormData sending empty objects via JQuery

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

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