Search code examples
phpjquerymysqlajaxlaravel

How to get image from DB & preview it in edit form using ajax in laravel?


I'm trying to get data from database using ajax in laravel. I get all the data & load that into edit form successfully except image. I got image from database but I couldn't preview it on edit form.

Here is my ajax call

         function editProduct(id, category_id) {
          $.ajax({
            url: "{{ url('admin/products/edit/') }}/" + id,
            type: "GET",
            contentType: false,
            cache: false,
            processData: false,
            dataType: "json",

            success: function(response) {
                $("#edit-modal").modal("toggle");
                $(".id").val(response.id);
                $("#edit_name").val(response.name);
                $("#edit_category").val(category_id);
                $("#edi_image").val();   <---What to do here?  --->

            }
        });


    }

Here is my controller code

public function edit($id) {
    $product = FoodItem::findOrFail($id);
    return response()->json($product);
}

I want to load image here

<img src='' id="edit_image" width="180px;" height="120" class="mt-2">
   <p>Old image</p>

Can anyone tell me how to do that?


Solution

  • I hope you are storing image path in DB and image in public assets. If that is the case then simply update the image src using jQuery

    $("#edi_image").attr('src','images/'+response.image); // change the path to your image