'Displaying images inside table using ajax and jQuery

I am sending requests to an API using AJAX and retrieving a response with JSON containing image name and various data with it.

I am trying to display these images in a html table but for some reason only 404 - img not found icons are displayed.

This is the code for generating the html from the AJAX response:

success : function(data){
    $('#t tbody#search').empty();
    if(data){
        $('#t tbody#all').hide();
        for (i = 0; i < data.length; i++) {
            $('#t tbody#search').append('' +
                '<tr><td> '+data[i].nom+' </td>' +
                '<td>'+data[i].prix+' </td>' +
                '<td>'+'<img src="{{asset('images/'~'+data[i].image +') }}"></td>'+
                '<td>'+data[i].quantite+' </td>'+
                '<td>'+data[i].descprod+' </td>  </tr>');
        };
    }

Could someone explain what is going on?



Solution 1:[1]

This looks like Laravel Blade syntax:

{{ asset(...) }}

But that code is being excecuted by Javascript. Laravel/Blade is not rendering this code, so that is not interpreted and converted into a URI here - it is just text to Javascript, and you'll just end up with that text in your <img src>. Use your browser's devtools and inspect the generated table, you will see this.

You have a few choices to solve this:

  1. If the back-end API where the data is coming from is your own application, just update it to include fully-qualified references to your images, so you don't need to do anything on the front end. Eg on the back end add something like:

    // Pseudo-code, you have to adjust for whatever you have
    $data['fullimage] = asset('images/' . $image);
    

    Then in your Javascript you can just do:

    '<td><img src="' + data[i].fullimage + '"></td>' + ...
    
  2. If you can't update the back end, you need to do what asset() normally does manually. Asset generates a URL based on the ASSET_URL you have in your .env file.

    • So say your ASSET_URL is http://yourwebsite/images/;

    • And an example data[i].image is a4b0ee1ff5f531edda05043231351231.jpeg

    • Then you can reference that in JS like this:

      '<td><img src="http://yourwebsite/images/' + data[i].image + '"></td>' + ...
      

    If this code is also running on http://yourwebsite/, then you don't even need that part, you can just use:

      '<td><img src="/images/' + data[i].image + '"></td>' + ...
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Don't Panic