I am trying to send form data via ajax to a nodejs server. Previously asked on this post.
Here's what my code looks like:
<div id="inputid" style="width: 400px; height:400px">
<p> Please enter a value between -90 and 90 for lat, and -180 and 180 before hitting
submit.</p>
<form id="sendCoordinates" action="http://localhost:8080/geodata" method="post">
MinLat: <input type="text" name="MinLat" value="15" id="minlat"><br>
MaxLat: <input type="text" name="MaxLat" value="25" id="maxlat"><br>
MinLong: <input type="text" name="MinLong" value="-10" id="minlong"><br>
MinLong: <input type="text" name="MaxLong" value="120" id="maxlong"><br>
<input type="submit" value="submit" id="s1">
</form>
<script>
$(document).ready(function() {
console.log("hi hi");
$("#sendCoordinates")
.on('submit', function(e) {
e.preventDefault();
var $form = $(e.target),
formData = new FormData(),
params = $form.serializeArray();
$.each(params, function(i, val) {
// console.log(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("hi helo");
}
});
});
});
</script>
</div>
My server side code looks like this :
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);
});
// for debugging purposes, just logging the request to check
// if request received
app.post("/geodata", function(req, res) {
console.log("hey");
console.log(req.body);
res.send("hi back!");
});
I am trying this out but I am unable to send the form successfully, and upon hitting submit, I get "hey" and an empty {} as logged output. I am not able to log the formData on the client side, regardless.
Can someone point out what I might be doing wrong?
You didn't assign a form to formData() that's why you're not sending any data to the server.
var myForm = $('#sendCoordinates')[0];
var formData = new FormData(myForm);
Related
I am using the Node.JS POST method to submit a form to my server. It is transmitted to the server fine; no problems occur at this stage. However, when I use io.emit with socket.io to transfer the data back to the client, nothing seems to happen client-side. Nothing is printed to the console and I'm getting no errors there or in Command Prompt (where I'm running the server from).
index.html:
<form id="schoolCreateForm" action="http://localhost:3000/createSchool" method="POST">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit">Submit</button>
</form>
<script>
var socket = io();
socket.on('updateSchool', function(response) {
console.log(response);
document.getElementById("headerSchoolName").innerHTML = data.schoolName;
});
</script>
app.js:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var io = require('socket.io')(serv);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.post('/createSchool', function(req, res) {
response = {
school_name: req.body.schoolName,
school_private: req.body.schoolPrivate,
entry_password: req.body.entryPassword
};
console.log(response);
res.sendFile(__dirname + '/client/index.html');
io.emit('updateSchool', response);
});
serv.listen(3000);
console.log("Server started on localhost://3000");
Does anyone know what's going on?
<form action="http://localhost:3000/createSchool" method="POST">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit" id="schoolCreateForm">Submit</button>
After submitting your form data it will reload your page, it means socket connection will be ended. If you want to see a response with socket make ajax.post request without reloading the page.
<form id="schoolCreateForm">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit">Submit</button>
</form>
<script>
document.querySelector('#schoolCreateForm').addEventListener('click',
function(e) {
e.proventDefault() // this line will not all to reload page after
/// submitting the
//form data
### writh you ajax request functionality here
})
var socket = io();
socket.on('updateSchool', function(response) {
console.log(response);
document.getElementById("headerSchoolName").innerHTML = data.schoolName;
});
My node.js code looks like this:
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic("WebDir")).listen(80, function(){
console.log('Server running on port 80...');
});
I would like to use an API and use the data from the input field in node.js
How can i exactly do it. The Input field is just a normal input field in HTML
You can create a simple test setup for this using Node.js Express..
2 files: index.js, index.html
index.html
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
var sendInput = function() {
var inputField = $('#inputField').val();
console.log(inputField);
$.ajax({
type: 'POST',
url: 'http://localhost:3000/inputData',
crossDomain: true,
data: JSON.stringify({ inputField: inputField }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result, status){
document.getElementById("output").innerHTML = result.nodeVariable;
},
error: function (errorMessage) {
console.error('Error: ', errorMessage);
}
});
}
</script>
</head>
<body topmargin="40" leftmargin="40">
<div id="result">Loading..</div>
</br>
<button onClick="sendInput()">Send input to Node.js</button> : <input type="text" id="inputField" value="test value"><br>
<div>
<br/>Result: <p id="output"></p>
<div>
</body>
</html>
Server side, this is the node.js script.
index.js
const bodyParser = require('body-parser');
const express = require('express');
const port = (process.env.PORT || 3000);
const app = express();
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.post('/inputData', (req, res, next) => {
console.log('/inputData post: ', JSON.stringify(req.body));
// Read the variable..
var inputField = req.body.inputField;
console.log('Input field: ', inputField);
res.status(201).send(JSON.stringify({status: 'OK', nodeVariable: inputField + " - updated by node."}))
});
app.listen(port);
console.log('Express listening on port ' + port);
Go to http://localhost:3000 on your browser to test.
I can successfully send a file to connect-busboy by using an HTML form's action attribute like so:
<form ref='uploadForm' method="post" action="http://localhost:3000/fileupload" enctype="multipart/form-data" id='uploadForm'>
Select file to upload:
<input type="file" name="sampleFile">
<input type="submit" value="Upload!">
</form>
However, I would prefer to not have my page redirect.
I tried to convert this to jQuery by removing the action attribute in the form tag and adding an onclick function with the following:
$.ajax({
url:'http://localhost:3000/fileupload',
type:'post',
contentType: 'multipart/form-data',
data:$('#uploadForm').serialize(),
success:function(){
alert('Success');
},
error: function() {
alert('Error');
},
});
Unfortunately, this doesn't work with the error:
TypeError: Cannot read property 'end' of undefined
The Nodejs code is as follows:
const express = require('express');
const busboy = require('connect-busboy');
const app = express();
app.use(busboy());
const fs = require('fs');
app.post('/fileupload', function(req, res) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
fstream = fs.createWriteStream(__dirname + '/files/' + filen ame);
console.log(fstream);
file.pipe(fstream);
fstream.on('close', function () {
res.send('Success');
});
});
});
var port = process.env.PORT || 3000;
app.listen(port);
Full error: http://i.imgur.com/vUqmjWS.png
By explicitly serializing the form you are implicitly avoiding/removing the multipart/form-data format. Instead, pass a FormData instance as the data. You can instantiate a new FormData from an existing form like:
var data = new FormData($('#uploadForm')[0]);
$.ajax({
url: 'http://localhost:3000/fileupload',
type: 'POST',
contentType: false,
processData: false,
cache: false,
data: data,
success: function() {
alert('Success');
},
error: function() {
alert('Error');
}
});
here is my client ajax code:
var sendData = JSON.stringify({
name: document.forms["token"].name.value,
password:document.forms["token"].password.value
});
$.ajax({
url:'http://localhost:8088/log/',
type:'POST',
contentType:'application/json',
data: sendData,
dataType:"json"
})
and here is my node server code:
const http = require('http');
const express = require("express");
const jwt = require('jwt-simple');
const moment = require('moment');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
var expires = moment().add(7,'days').valueOf();
var token;
app.set("jwtTokenSecret","luo");
app.use(bodyParser.urlencoded({ extended: false }));
app.all("/log",function(req,res){
var name = req.body.name;
var password = req.body.password;
console.log(name,password)
...
}
I found that the name and password are both undefined in node server, the json data on client is correct. I have tried a lot to solve it , but I can't, I need your help, thanks.
$.ajax already serialize data, so, is not necessary to use JSON.stringify if you already set dataType to 'json'.
Try to send data as plain object.
In my case i make ajax call something like this.
From client side make the ajax call:
function _sendData(){
var host= 'localhost'; //or you can set your host by your choice.
$.post(host+'/post',$('#horizontalForm').serialize(),function(response){
// respose
});
}
From node.js server side code given below,
var qs = require('querystring');
app.post('/post',function(req,res){
if(req.method=='POST'){
var body='';
req.on('data',function(data){
body+=data;
console.log("before proccess = "+body);
if (body.length > 1e6) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
request.connection.destroy();
}
})
req.on('end',function(){
var post = qs.parse(body);
console.log(post.user);
console.log(post.message);
})
}
})
and the HTML part be like,
<form method="POST" action="/post" id="horizontalForm">
<p class="lead">
<input type="text" name="user" value="testUser" id="userId"/>
<div>
<input type="text" name="message" id="messageId"/>
<input type="button" value="Send" class="btn btn-lg btn-default" id="getData" onclick="_sendData();"/>
</div>
</p>
</form>
N.B : To install query string you can run the command npm install querystring --save
Don't forgot to include jquery.js and ajax lib in your html.
Check document.forms["token"] contains name and password by using console.log('values',document.forms["token"]) expression .
If values are there ,
Then call the api,
var sendData = {
name: document.forms["token"].name.value,
password: document.forms["token"].password.value
};
var saveData = $.ajax({
url: 'http://localhost:8088/log/',
type: 'POST',
contentType: 'application/json',
data: sendData,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
I'm running a server in nodejs with express to serve an html form within the file index.html to a client like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
app.get('/', function(req, res){res.sendfile('index.html');});
app.post('/', function(req, res){
res.json(req.body);
});
app.listen(8080);
req.body gives me the form input. Now I need to send back req.body to the client, and to do this I'm using ajax on the client side (inside index.html) like this:
var data;
$('#submit').click(function()
{
console.log('Button Clicked');
$.ajax({
url: '/',
type:'POST',
data: data,
dataType: 'json',
}).done(function(data) {
console.log(data);
});
})
However when I click the button submit I get Object {} in the browser console and not the form input.
What am I missing here?
There are two issues in your code:
First, as the comments mention, bodyParser() is deprecated, you should be using the specific bodyParser middlewares (json, text, urlencoded, raw). So in your case:
app.use(bodyParser.json())
Second, your client side call to jQuery.ajax should stringify your data. Like this:
$('#submit').click(function()
{
console.log('Button Clicked');
$.ajax({
url: '/',
type:'POST',
data: JSON.stringify(data),
dataType: 'json',
}).done(function(data) {
console.log(data);
});
})