简体   繁体   中英

ajaxForm not submitting on file input select change

Hey guys I'm trying to submit a simple form with a file input type in it. The challenge is that I want the submission to occur on file select.

My form is as follows:

<form id="uploadForm" action="submit.php" method="post" enctype="multipart/form-data">
    <div class="fileUpload btn btn-lg btn-primary">
        <span>Choose File</span>
        <input id="imageBtn" type="file" class="upload" name="image"/>
    </div>
</form>

My JavaScript is as follows:

$("input#imageBtn").change(function () {
        console.log("submitting...");
        // bind to the form's submit event
        $('#uploadForm').submit(function() {
            console.log("submitting...form");
            $('#uploadForm').ajaxSubmit();
            return false;
        });
});

For some reason I only see "submitting..." in my console and nothing beyond that and nothing gets submitted.

Any help would be greatly appreciated!

Thank you.

From jQuery documentation:

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to elements. Forms can be submitted either by clicking an explicit input type="submit", input type="image", or button type="submit", or by pressing Enter when certain form elements have focus.

https://api.jquery.com/submit/

Try adding an appropriate tag like

<input id="imageBtn" type="file submit" class="upload" name="image"/>

The following seems to work.

<form id="imgForm" action="action.php" method="post" enctype="multipart/form-data">
        <div class="fileUpload btn btn-lg btn-primary">
            <span>Choose File</span>
            <input id="imageToBeUploaded" type="file" class="upload" name="image"/>
        </div>
</form>

$("body").on('submit', '#imgForm', function(){
    $(this).ajaxForm({target:'#uploadStatus'});
    console.log("submitting...");
    return false;
});

/* Uploading Profile BackGround Image */
$('body').on('change','#imageToBeUploaded', function() {
    //submit the form
    $("#imgForm").submit();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM