1

I'm trying to upload image in lravel 5 via ajax Hear is my HTML form

<form role="form" method="POST" action="/save-doctor" id="add_doctor" enctype="multipart/form-data">
{!! csrf_field() !!}
<input name="photo" type="file" id="imgInp" accept="image/png, image/jpeg,image/jpg" onchange="readURL(this);">
<input type="email" class="form-control" name="email" id="email"">
</form>

I send a ajax request by this script

$(document).ready(function(){
            $("#add_doctor").submit(function(e){
                e.preventDefault();

                $.ajax({
                    url : '/save-doctor',
                    type : 'POST',
                    data : {
                        'photo' : $('input:file[name=photo]').val(),
                        'email' : $('input[name=email]').val(),
                        '_token': $('input[name=_token]').val()
                    },
                    success : function(data){
                        console.log("Sucess");
                        console.log(data);
                    },
                    error : function(data){
                        console.log("error");
                        console.log(data);
                    }
                });
            });
});

Ajax always give me a full file path not a file. how can i upload an image or a file via ajax in laravel . thank you advance .

1 Answer 1

1

you can create a new Form object and send it to your controller

$(document).ready(function (e) {
    $('#add_doctor').on('submit',(function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    }));

    $("#imgInp").on("change", function() {
        $("#add_doctor").submit();
    });
});
Sign up to request clarification or add additional context in comments.

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.