Home > OS >  view image with Select box using laravel
view image with Select box using laravel

Time:04-08

I have been able to display the data at this link: [https://stackoverflow.com/questions/71755911/filled-many-textbox-with-select-box-using-laravel][1] but i can't display the image, does anyone know the solution? thx

my controller

public function getpengarang_buku(Request $request)
    {
        $kode_buku = $request->kode_buku;
        $perpustakaan = M_Perpustakaan::where('kode_buku', $kode_buku)->get();

        $data = [];
        foreach($perpustakaan as $buku){
        $img_url = asset('storage/ft_perpus/'.$buku->foto_buku);
        $data = ['pengarang_buku' => $buku->pengarang_buku,
            'penerbit_buku' => $buku->penerbit_buku,
            'img_url'=>$img_url];
    }
        return response()->json($data);
    }

my script

$(function()
{
    $('#judul_buku').on('change', function(){
        let kode_buku = $('#judul_buku').val();

        // console.log(kode_buku);
        $.ajax({
          headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
          type : 'POST',
          url : "{{ route('getpengarang_buku') }}",
          data : {kode_buku:kode_buku},
          cache : false,

         success: 
          function(msg){
            $('#pengarang_buku').val(msg['pengarang_buku']);
            $('#penerbit_buku').val(msg['penerbit_buku']);
            $('#img_url').val(msg['img_url']);
          }
}
        })
    })
});

my blade.php

<img src="{{ img_url }}" id="foto_buku" name="foto_buku">

error message : Undefined constant "img_url". any one can help? thx

CodePudding user response:

the error error message : Undefined constant "img_url", mean the php trying to find the const variable of "img_url" that doesn't exist

so in your case, you can use the javascript to change the image, since the image data is requested via ajax

beacuse you using JQuery you can do like this success function on ajax request

function(msg){
  $('#pengarang_buku').val(msg['pengarang_buku']);
  $('#penerbit_buku').val(msg['penerbit_buku']);
  $('#foto_buku').attr('src',msg['img_url']); // change the src on image tag with foto_buku id
}

or you can use vanilla js to change the value on img scr

document.getElementById("foto_buku").src = msg['img_url'];
  • Related