mercredi 10 octobre 2018

Adding an image to an upload in ajax

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 and break the form which was working -- the form does nothing on the button click (nothing shows in the console to say its worked not worked).

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::hidden('user_id', Auth::user()->id, array('class' => 'userid'))  !!}
   
   

      
      {!! 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 = $('.image1').prop('files')[0];
        var form_data = new FormData();
        form_data.append('title', title);
        form_data.append('review', comment);
        form_data.append('userid', userid);
        form_data.append('image', image);
        dl.preventDefault();
        $.ajax({
            method: 'POST',
            url: urlCreateReview,
            data: form_data,
            processData: false,
            contentType: false
        })
                .done(function() {

        });

    });



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire