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

11,697

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!

Share:
11,697

Related videos on Youtube

Serg Nights
Author by

Serg Nights

Updated on August 22, 2022

Comments

  • Serg Nights
    Serg Nights about 1 year

    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!

    • barry-johnson
      barry-johnson over 9 years
      Please see if this question and its answers helps you. To be clear, the answers in it are about solving it with Javascript or even JQuery.
    • Ishank Gupta
      Ishank Gupta over 9 years