How to Submit Form with Ajax in NodeJS App
Published: 2023-07-26 11:04:54

In this demo, We will discuss about form submittion with Ajax without page refresh. Simply if anywhere we don't want to use angular or any other js framework then we can do the similar task with Ajax.
Let's have a look over folder structure we have for this task

``````node_modules/

uploads/

index.html

package-lock.json

package.json

server.js``````

Lets start discussing from bottom to top. So have a look on the code inside **server.js**

``````let express = require("express"),
multer = require('multer'),
crypto = require('crypto'),
fileExtension = require('file-extension'),
app = express();
 
let storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads')
},
filename: function (req, file, callback) {
crypto.pseudoRandomBytes(16, function (err, raw) {
callback(null, raw.toString('hex') + Date.now() + '.' + fileExtension(file.mimetype));
});
 
 
}
});
 
let upload = multer({ storage : storage}).single('image');
 
app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
// method to accept request from the file
app.post('/api/form-submit',function(req,res){
 
upload(req,res,function(err) {
console.log(req.body,'other form data---');
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
 
app.listen(3000,function(){
console.log("App listening on port: 3000");
});
 ``````

In the above file, at the top we have included the basic package to create a app. Below that we have set the multer for file upload patha and file renaming. Below that we have a method  to accept the form request  **/api/form-submit.** This method does the actual task at server side.

Now move to the next file named **package.json**

``````{
"name": "form_submit_using_ajax",
"version": "1.0.0",
"author": "Suraj Roy",
"keywords": "N/A",
"description": "N/A",
"dependencies": {
"express": "4.13.3",
"file-extension": "^4.0.5",
"multer": "1.1.0"
},
"devDependencies": {
"should": "~7.1.0",
"mocha": "~2.3.3",
"supertest": "~1.1.0"
}
}
 ``````

In the package.json, we can see the needed package with version and basic detail of the app. package-lock.json is created automaticallly while installing packages so no need to worry about the content inside that file.

Now lets move to the html file i.e., **index.html.** In this file we have two things first is form for picking file inputs and seconds is script part to submit the request using ajax.

**Form section**

``````<form id="uploadForm" enctype="multipart/form-data" action="/api/form-submit" method="post">
<input id="file" type="file" name="image" />
<label>name :</label><input type="text" name="name" />
<input type="submit" value="Upload Image" name="submit">
<span id = "status"></span>
</form>``````

**Script section**

``````<script>
$(document).ready(function() {
 
$('#uploadForm').submit(function() {
$("#status").empty().text("File is uploading...");
$(this).ajaxSubmit({
error: function(xhr) {
status('Error: ' + xhr.status);
},
 

success: function(response) {
$("#status").empty().text(response);
console.log(response);
}
});
//Code to disable the page refresh.
return false;
});
});
</script>``````

By following these easy steps we can perform the required tak very easily. You can download the complete zipped demo code for this site also.

Let me know your thoughts over the email **demo.jsonworld@gmail.com.** I would love to hear them and If you like this article, share with your friends. 

Thanks!!

This article is originally posted over [jsonworld](jsonworld.com)