Search code examples
javascriptjquerypromisesubmitcroppie

Can't submit form inside a then()


I am trying to submit a form with an image into a php page, i'm using croppie to crop an image and put the result inside an "input" file element, and after that i wish to submit my form.

my js:

$('#submit-button').on('click', function(e) {
    $('#imagePreview').croppie('result', {
       type: 'canvas',
       size: 'viewport'
    }).then(function (resp) {
       $('#fileInput').val(resp);
       $('#ppForm').submit();
    });
});

my html:

<form id="ppForm" enctype="multipart/form-data" action="upload_profile_picture.php" method="post">
   <input id="fileInput" name="fileInput" type="file" accept="image/*" onchange="displayPreview(this)" required>
   <img id="imagePreview" class="croppie-container">
   <input type="button" value="submit" id="submit-button"/>
</form>

The problem is, this line $('#ppForm').submit(); gets skipped for some reason (i've debugged the js using javascript and i see that $('#fileInput').val(resp); runs and puts the cropped value into the input, but then the code just ends and no submit happens). I've also tried to put a break point on that line but it never reaches there. Why is the submit ignored?


Solution

  • You can't set the value of a input type="file" other than to clear it. From the spec:

    input . value [ = value ]

    Returns the current value of the form control.

    Can be set, to change the value.

    Throws an "InvalidStateError" DOMException if it is set to any value other than the empty string when the control is a File Upload control.

    (my emphasis)

    Presumably, you're getting that exception from val, which is why the form isn't submitted.