4

Good day, I have a form for sending fields and file to node.js server. On server the data parsed by Formidable. Everything is working good, but after form submitted it loads a page with a response. Does anyone know either the way to send the data with standard form mechanisms and not reload page (jQuery ajax method with serialize will not work because of file in form) either write such response on server so it will not trigger page reload. Form:

<form action="/upload" enctype="multipart/form-data" method="post" id="eventForm">
<label>Date</label>
<input type="text" name="date"/>
<label>Image</label>
<input type="file" multiple="multiple" name="picture" />
<input type="submit" value="Submit!" />
</form>

Server side:

app.post('/upload', function (req, res) {
    var form = new formidable.IncomingForm();
    // save file code goes here 
    form.parse(req, function(err, fields, files) {
        //response code goes here
        res.send('done');
    });
});

Any better ways to do this? Thank you!

Serg Nights
  • 141
  • 1
  • 1
  • 7
  • 1
    Please see if [this question](http://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery) and its answers helps you. To be clear, the answers in it are about solving it with Javascript or even JQuery. – barry-johnson Mar 04 '14 at 05:01
  • 1
    have a look at http://blog.w3villa.com/programming/upload-image-without-submitting-form-works-on-all-browsers/ – Ishank Gupta Mar 04 '14 at 05:30
  • 1
    what did you do? I see you accept the answer but I dont know if it works for me. – Tenz Feb 13 '18 at 17:14

1 Answers1

10

Thanks to both of people who answered in comments to my question! Both of their solutions are working and here they are:

1) Easiest: add invisible iframe after the form and specify it as a target of a form:

<form action="/upload" enctype="multipart/form-data" method="post" id="eventForm" target="uploader_iframe">
//....
</form>
<iframe id="uploader_iframe" name="uploader_iframe" style="display: none;"></iframe>

2) Correct: actually it is not that hard to use AJAX to send the same data, you just need to specify some parameters to make it work right. Here is a code:

$('#eventForm').submit(function (e) {
        e.preventDefault();
        var fd = new FormData($(this)[0]);
        $.ajax({
            url: '/upload',
            data: fd,
            processData: false,
            contentType: false,
            type: 'POST',
            success: function(data){
                console.log(data);
            }
        });
});

Thank you both commentators! Use their links to find more about it!

Serg Nights
  • 141
  • 1
  • 1
  • 7