Home > OS >  JQuery Ajax Form Submit with Form Data returns nothing on submit
JQuery Ajax Form Submit with Form Data returns nothing on submit

Time:12-24

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 >                    
        <div >
            <label>Name</label>
            <input type="text"   name="name" required>
        </div>
        <div >
        <label>Classes</label>
         <select  name="classes">
         <option value="Direct">Direct</option>
         <option value="Merketing">Merketing</option>
         <option value="Partnets">Partnets</option>
         </select>
        </div>  
        <div >
        <label>File</label>
         <input type="file"   name="file">
        </div>                  
    </div>
    <div >
        <input type="submit"  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

CodePudding user response:

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);   
});
  • Related