简体   繁体   English

jQuery提交表单输入类型“文件”更改的表单

[英]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 , 我正在基于图像选择提交表单,因此文件输入更改将提交表单,问题是它将我重定向回与使用laravel相同的路线,

Jquery Code : jQuery代码:

$('#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 : 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){} 注意: var profileImageForm = $("#profileImageForm")返回一个数组,我不知道表单如何成为数组,所以我正在提交诸如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()和form.on('submit',function(){})不同。 form.submit() will only submit your form and doesn't accept any parameters. form.submit()仅提交您的表单,不接受任何参数。 So your function in submit is ignored. 因此,您在Submit中的功能将被忽略。 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. 问题可能出在您的Laravel控制器中。 Please check the return action of your controller. 请检查控制器的退回动作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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