ImTalkingCode
ImTalkingCode

Reputation: 385

File upload document.ready .on('submit') submitted twice

Using node.js/express/jade. I want to upload a file without a page refresh, so using a .on('submit') function in the document.ready() function as below. The problem is the POST is happening twice and I can't figure-out why. Help would be awesome.

HTML:

<form id="upSchema" action="/setVSSUP/6" enctype="multipart/form-data" method="post">
    <table id="tblSFU" class="table table-striped table-hover table-condensed">
        <tbody>
            <tr id="sVSFU">
                <td>
                    <input type="file" name="schemadoc">
                </td>
                <td>
                    <button onclick="onSSFUp(6)">Upload</button>
                </td>
            </tr>
        </tbody>
    </table>
</form>

Client-side Javscript:

function onSSFUp(key) {
  $('#upSchema').submit();
}

Document.ready:

$(document).ready(function() {
  $(document).on('submit','#upSchema', function(e) {
    $('#schup').text('Starting Upload...');
    e.preventDefault();
    $(this).ajaxSubmit({
      error: function(xhr) {
        $('#schup').text('Error: '+xhr.status);
      },
      success: function(res) {
        $('#schup').text('File upload Success: '+res.name);
      }
    });
    document.getElementById('btnSSFU').disabled = false;
    return false;
  });
});

Resulting console:

POST /setVSSUP/6 200 81ms
POST /setVSSUP/6 200 114ms

Upvotes: 0

Views: 687

Answers (1)

markle976
markle976

Reputation: 967

The button inside the form is triggering it to be submitted. You are then adding an additional onclick event to the button (onSSFUp(6)). Remove the onclick event and you will see the form still gets submitted when you click the button.

Upvotes: 1

Related Questions