Prevent page reload after form submit / node (no ajax available)

Serg Nights picture Serg Nights · Mar 4, 2014 · Viewed 11.2k times · Source

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!

Answer

Serg Nights picture Serg Nights · Mar 5, 2014

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!