0
votes

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 ?

3

3 Answers

1
votes

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();
0
votes

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

0
votes

you can prevent this by adding e.stopPropagation()