smartnathan's avatar

Image not Uploading in AJAX request.

Good afternoon, please i have an issue uploading an image when I make an Ajax request. But using a default server action of uploading the image it works perfectly well. Please, is there anything i have not done well in the ajax code. Thanks for your help.

View Code

{!! Form::open(['url' => '/admin/notes', 'id' => 'note-form', 'class' => 'form-horizontal', 'files' => true]) !!}

<input autofocus type="text" name="title" class="form-control" placeholder="Write note title..." {{old('title')}} />

  <select id="group" name="class[]" class="chosen" multiple data-placeholder="Choose a class or many classes">
        <option value=""></option>
        @if (isset($user_classes))
        @foreach ($user_classes as $class)
        <option value="{{$class->pivot->group_id}}">{{ $class->name }}</option>
        @endforeach
        @endif
</select>

<input type="file" name="image" id="image">

{!! Form::close() !!}

Controller Code

$requestData = $request->except('image');
        if ($request->file('image') != null) {
        $image = $request->file('image');
        $new_image = time() . "." . $image->getClientOriginalExtension();
 
          $image->move(
        base_path() . '/public/uploads', $new_image
    );
        }

        foreach ($requestData['class'] as $group) {
            $new_note = new Note;
        $new_note['user_id'] = Auth::user()->id;
        $new_note['group_id'] = $group;
        if (isset($requestData['title'])) {
        $new_note['title'] = $requestData['title'];
        }
         if (isset($new_image)) {
      $new_note['image'] = $new_image;
          }
        $new_note['body'] = $requestData['body'];
        $new_note['visibility'] = 1;
        $new_note->save();
        }

        if ($request->ajax()) {
            return response()->json(['message' => 'Note was successfully submitted!']);
        } else {
            return redirect('admin')->with('flash_message', 'Your note was successfully added to your class.');
        }

Ajax Code


$('#submit-note').on('click', function(event) {
    event.preventDefault();
$.ajax({
        url: "{{ url('/admin/notes')}}",
        type: "POST",
        dataType: "JSON",
        data: $("#note-form").serialize();,
        success: function(data) {
             if (data) {
                //console.log(data);
                 swal("Completed!", data.message, 'success');
                $('#note-form').trigger('reset');
                } else {
                   swal("Failed!", 'Comment was unable to be submitted, try again', 'error');
                }
        },
        error: function(data) {
            if (data.status === 422) {
                errors = '<div class="alert alert-danger">';
                $.each(data.responseJSON.errors, function(key, value) {
errors += '<li>'+value+'</li>';
                })
              errors +=  '</li></div>';
                $('#errors').html(errors);

            }

        }

    });

    });

0 likes
9 replies
tykus's avatar

You can't simply serialize a form if you want to upload an image; you will need to use the FormData API, e.g.

let formData = new FormData();
formData.append('image', document.getElementById('image').files[0]);

$.ajax({
        url: "{{ url('/admin/notes')}}",
        type: "POST",
        data: formData,
    // ...
});
jlrdw's avatar

Could you show as answered, and perhaps show the entire final solution to help others.

I give @tyronix (combo of both) best answer.

1 like
smartnathan's avatar

Here is the working Ajax code for image upload using formData API

You will need a SweetAlert library for a lovely alert box

$('#note-form').on('submit', function(e) {
    e.preventDefault();

    let noteFormData = new FormData(this);
noteFormData.append('image', document.getElementById('image').files[0]);
    swal({
        title: 'Are you Sure?',
        text: 'Please! Confirm that you are ready to publish note.',
        type: 'info',
        showCancelButton: true,
        closeOnConfirm: false,
        showLoaderOnConfirm: true,
    }, function(){
        setTimeout(function(){

$.ajax({
        url: "{{ url('/admin/notes')}}",
        type: "POST",
        data: noteFormData,
        contentType: false,
        processData: false,
        cache: false,
        success: function(data) {
             if (data) {
                 swal("Completed!", data.message, 'success');
                $('#note-form')[0].reset();
                } else {
                   swal("Failed!", 'Comment was unable to be submitted, try again', 'error');
                }
        },
        error: function(data) {
            if (data.status === 422) {
                errors = '<div class="alert alert-danger">';
                $.each(data.responseJSON.errors, function(key, value) {
errors += '<li>'+value+'</li>';
                })
              errors +=  '</li></div>';
                $('#errors').html(errors);

            }

        }

    });

        }, 2000);
    });

});
jlrdw's avatar

Thanks for posting, with so many questions about uploading with ajax, I try to save some of the replies to answer future questions. This one turned out a good one.

Please or to participate in this conversation.