简体   繁体   中英

Jquery submit form on form input type 'file' change

I am submitting a form on the base of image selection, So file input change will submit the form, The issue is that it redirects me back to the same route as i am using laravel ,

Jquery Code :

$('#profile-image-upload').change(function(e){

    var profileImageForm = $("#profileImageForm");

    profileImageForm[0].submit(function(e){

        e.preventDefault();
        var file_data = $('#profile-image-upload').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);

        $.ajax({
            url: "/freelance/change-profilePic",
            data: form_data,
            type: 'POST',
            success: function (data) {
                console.log('Success');
            },
            error: function (xhr, status, error) {
                console.log('error');
            }
        });
    });
});

HTML :

<div class="profile__img">
    <form id="profileImageForm" method="post" enctype="multipart/form-data">
        <input id="profile-image-upload" class="" name="file" type="file">
    </form>

    <img src="{{asset('freelance/img/demo/people/3.jpg')}}" alt="" id="profile-image">
</div>

Note: var profileImageForm = $("#profileImageForm") returns an array which i have no idea how a form can be an array, So i am submitting form like profileImageForm[0].submit(function(e){}

Got idea why form submit redirecting ?

You are submitting your form but not listening submit event. form.submit() and form.on('submit', function(){ }) are different. form.submit() will only submit your form and doesn't accept any parameters. So your function in submit is ignored. Instead of using

profileImageForm[0].submit(function(e){ });

use

profileImageForm.on('submit', function(e){
   e.preventDefault();
   //
   // your uploader code goes here;
   //
}).submit();

The problem is probably in your Laravel controller. Please check the return action of your controller.

您可以通过添加e.stopPropagation()来防止这种情况

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