0

Okay so this problem has been solved multiple times but mine is a bit more complicated. The following is my AJAX which takes as input Text fields and image and submits the fields and file path to the database.

$(function () {

    $('form#data').off('submit').on('submit',function () {
        var formData = new FormData($(this)[0]);

        $.ajax({
            type:'POST',
            url: 'upload.php',
            data: formData,
            async:false,
            cache:false,
            contentType: false,
            processData: false,
            success: function (returndata) {$('#result').html(returndata);}
        });
        return false;
    }); 
});

Now when I submitted a file it was uploaded normally. Then if I tried submitting a second file, it created multiple copies on the database. And it went on exponentially increasing as I went on uploading further.

So I looked up and saw that bind/ unbind and on/off were two solutions.

This worked for for the second file uploaded, but from the third file onwards the repetition continued.

Please let me know where i am going wrong.

Thanks.

hal9000
  • 201
  • 5
  • 25
  • you can check this out .. http://stackoverflow.com/questions/2830542/prevent-double-submission-of-forms-in-jquery – Sandeep J Patel Sep 27 '16 at 15:13
  • are you calling the containing function multiple times? Normally you'd only ever attach a click handler once. – Marc B Sep 27 '16 at 15:19
  • @MarcB its a form to upload various images. So calling function every time I click submit. I need to do that 20 times in a row for 20 files. – hal9000 Sep 27 '16 at 15:22
  • calling the submit handler is fine. but normally you'd only attach it ONCE, so there should be no need for the .off call, unless you execute the whole `.on(...)` multiple times. – Marc B Sep 27 '16 at 15:23
  • @MarcB could you point at what exactly I should change in the code? I just started web development, so am unable to understand completely what you are saying. Thanks. – hal9000 Sep 27 '16 at 15:26
  • @SandeepJPatel that is not the issue I am facing. – hal9000 Sep 27 '16 at 15:41

1 Answers1

0

Okay so I solved it. I removed the on off and did this. Now works fine!

$(function () {
        $('form#data').submit(function (e){
            e.preventDefault();
             e.stopImmediatePropagation();
            var formData = new FormData($(this)[0]);
            $.ajax({
                type:'POST',
                url: 'upload.php',
                data: formData,
                async:false,
                cache:false,
                contentType: false,
                processData: false,
                success: function (returndata) {$('#result').html(returndata);}
            });
            return false;
        }); 
});
hal9000
  • 201
  • 5
  • 25