Search code examples
javascripthtmlformssubmitsingle-threaded

Javascript form submit waiting till finishes


I have a form with upload

<form action="../upload" method="post" id="upload_form" enctype="multipart/form-data" target="upload_frame" >
        <input name="file" type="file" />
    </form>

and it's submit using javascript form another form submit button

function upload(){
    var uploadForm = document.getElementById('upload_form');

    uploadForm.submit();
    console.log('this should be called when the form finishes upload and respone is committed');

}

please tell if the example is not clear enough


Solution

  • Add an onload handler to your iframe. It will be called after the server responds to the request.

    For example:

    var uploadFrame = document.getElementsByName('upload_frame')[0];
    
    function handleResponseReceived() {
        console.log('this should be called when the form finishes upload and respone is committed');
    }
    
    if (uploadFrame.addEventListener) {
        uploadFrame.addEventListener('load', handleResponseReceived, false);
    }
    else {
        uploadFrame.attachEvent('onload', handleResponseReceived);
    }