mercredi 10 octobre 2018

Adding an image upload to an Ajax/Laravel form

I have created a form where i upload data to the database with ajax on a button click, i have tried to add an image(file) upload to the form but it seems to make an error on the form and the form does nothing on the button click.

Can anyone see where i am going wrong?

PHP:

$product = Product::find($products_id);
        $comment = new Comment();
        $comment->title = $request['title'];
        $comment->ratings = $request['rating'];
        $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">
      
      
      
       <select class="form-control rating" name="ratings">
           <option value="1">Very Poor (1 Star)</option>
           <option value="2">Poor (2 Star)</option>
          <option value="3" selected="selected">Fair (3 Star)</option>
           <option value="4">Good (4 Star)</option>
          <option value="5">Excellent (5 Star)</option>
        </select>
      </div>
      <div class="comment-form">
         
          
          {!!Form::hidden('user_id', Auth::user()->id, array('class' => 'userid'))  !!}
          
          

       </div>
       <div class="submit-comment">
          
          {!! Form::close() !!}
       </div>

JS AJAX:

$('.send-review').on('click', function(dl) {

    var title = $('.title').val();
    var rating = $('.rating').val();
    var comment = $('.review').val();
    var userid = $('.userid').val();
    var image = $('.image').val();


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

    });

});



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire