简体   繁体   中英

JQuery Ajax Form Submit with Form Data returns nothing on submit

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 class="modal-body">                    
        <div class="form-group">
            <label>Name</label>
            <input type="text" class="form-control"  name="name" required>
        </div>
        <div class="form-group">
        <label>Classes</label>
         <select class="form-control" name="classes">
         <option value="Direct">Direct</option>
         <option value="Merketing">Merketing</option>
         <option value="Partnets">Partnets</option>
         </select>
        </div>  
        <div class="form-group">
        <label>File</label>
         <input type="file"  class="form-control" name="file">
        </div>                  
    </div>
    <div class="modal-footer">
        <input type="submit" class="btn btn-success" 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM