Adding an image upload to an AJAX post form

Posted 1 month ago by dionarap

I've created a form where I upload data to the database with Ajax on a button click. I've tried to add an image (file) upload to the form but it seems to generate an error on the form -- the form does nothing on the button click.

Can anyone see where I'm going wrong?

PHP: $product = Product::find($products_id); $comment = new Comment(); $comment->title = $request['title']; $comment->comment = $request['comment']; $comment->products()->associate($product); $comment->user_id = $request['userid']; $comment->save();

    if ($request->hasFile('image')) {
    $picture = new Picture();
    $image = $request->file('image');
    $filename = uniqid('img_') . '.' . $image->getClientOriginalExtension();
    $location = public_path('images/' . $filename);
    Image::make($image)->save($location);
    $picture->image = $filename;
 $picture->products()->associate($product);
    $picture->user_id = $request->user()->id;
    $picture->comments()->associate($comment);
    $picture->save();

}

HTML

    {!! Form::open((['route' => ['comments.store', $product->id], 'method' => 'POST', 'files' => 'true'])) !!}
     <div class="comment-form">
     {{ Form::label('title', 'Title (Give a short summary)') }}
     {{Form::text('title', null, ['class'=>'form-control title', 'minlength'=>'2','maxlength'=>'30'])}}
      {{Form::label('comment', 'Add comment (2000 character limit)')}}
       {{Form::textarea('comment', null, ['class'=>'form-control review'])}}
       {!!Form::hidden('user_id', Auth::user()->id, array('class' => 'userid'))  !!}
       {{Form::label('image', 'Upload image')}}
       {{ Form::file('image', null, array('class' => 'image')}}

          {{ Form::submit('Add Review', ['class' => 'btn btn-send btn-block send-review'])}}
          {!! Form::close() !!}
     </div>

JS AJAX:

$('.send-review').on('click', function (dl) {
 var title = $('.title').val();
    var comment = $('.review').val();
    var userid = $('.userid').val();
    var image = $('.image').val();

 dl.preventDefault();
 $.ajax({
     method: 'POST',
     url: urlCreateReview,
     data: {title: title, comment: comment, userid: userid, image: image}
    }).done(function () {
 });
});

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.