Search code examples
jqueryjsondatatables

Insert JSON value in AJAX response


I'm filling dynamically a table and I got stuck when I was trying to concatenate or insert a value to JSON which I get from controller. I want to insert this value because I need to show an image, so I insert an HTML-tag with a route which comes from JSON.

Here's my code:

Controller

public function consultaProd2(Request $request)
{
    $almacenes = Almacen::orderBy('nombre')->lists('nombre', 'id'); 
    $fechas = explode(' ', $request['RangoFecha']);
    $fechaInicial = $fechas[0].' 00:00:00';
    $fechaFinal = $fechas[2].' 23:59:59';

    $productos = Producto::whereBetween('created_at', [$fechaInicial, $fechaFinal])
                     ->where('almacen_id', '=', $request['Almacen'])
                     ->get();
    return response()->json($productos);
}

Script

<script type="text/javascript">
    function llenar(response, index, value)
    {
        $('#example1').DataTable({
            "destroy": true,
            "data": response,
            "scrollX": true,
            "columns":[
                {"data":"img"},
                {"data":"id"},
            ]

        });
    }
</script>

<script type="text/javascript">
    function consultaProducto(){
        var tablaDatos = $('#datos');
        var token = $("#token").val();
        var route = '<?= url('producto/consultaProducto') ?>'
        var data = {};
        data.Almacen = $('select[name=Almacen]').val();
        data.RangoFecha = $('input[name=RangoFecha]').val();
                $.ajax({
                    url: route,
                    headers: {'X-CSRF-TOKEN': token},
                    data: data,
                    method: 'POST',
                    statusCode: {
                        400: function() {
                        }
                    }
                }).done(function(response){
                    $.each(response, function(index, value){
                        if(response[index].pathImg == null)
                            var img = "/documento/valach/noimg.png";
                        else
                            var img = response[index].pathImg;
                        var img = "/documento/valach/noimg.png";
                        response[index].img = "<img src="+img+">";
                        //console.log(response);
                        llenar(response, index, value);
                    });

                }).fail(function(response){
                }); 
            }
        }
        return false;
    }

For example, if the query gets 3 arrays and I print the id it only shows the information without any error, but when I use data:img which is the value I did insert, it throws me the following error, after that it fills the table and shows the image.

Error image here

and the row increases as information arrives, but if I only get 1 array in query, it fills the table without any error. Hope you can help me, thanks.


Solution

  • You call llenar() inside the loop, i.e once for each iteration. You should call it after the loop has finished. And you should really use some { }'s to avoid confusion when you (or others) reinvestigate the code in 3 weeks time :)

    $.each(response, function(index, value){
      var img;
      if (response[index].pathImg == null) {
       img = "/documento/valach/noimg.png";
      } else {
       img = response[index].pathImg;
      }
      //var img = "/documento/valach/noimg.png"; ???
      response[index].img = "<img src="+img+">";
    });
    llenar(response, index, value);