0

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 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

The controller just returns a string.'
0

you can prevent this by adding e.stopPropagation()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.