syszen's avatar

laravel jquery ajax json response is string

i have a problem with the response of json.. so i have this script

<script type="text/javascript">
        $('#tiposeguro').change(function(){
            var hidden = $('input[type=hidden]#tipo')
            var tipo = hidden.val();
            var id = $(this).val();
            var seguro = 1;
            var url = hidden.attr('data-url');
            url = url.substring(0, url.length-1);
            url = url + id;
            $.ajax({
                type: "GET",
                dataType: 'json',
                url: url,
                data:{
                    'tipo': tipo,
                    'id': id,
                }
            })
            .done(function( response ) {
                $('li').empty();
                console.log(response)

                $( ".garantias" ).prepend( '<li><input type="checkbox" name="garantias[]" value="1"/>&nbsp;</li>' );
            })
            .fail(function( response ) {
                console.log( "Error: ");
            });
        });
    </script>

on console

Object {garantias: "[{"id_garantia":1,"descricao":"garantia carro 1","…escricao":"garantia carro 6","atributo":"66666"}]"}
garantias
:
"[{"id_garantia":1,"descricao":"garantia carro 1","atributo":"11111"},{"id_garantia":2,"descricao":"garantia carro 2","atributo":"22222"},{"id_garantia":6,"descricao":"garantia carro 6","atributo":"66666"}]"

when i do response.garantias[0] for example i get "[" and not 1 (id_garantia) when response.garantias[1] is "{" thisis like a string but in my controller i have ($garantiasPossiveis is a query from database , objects )

Response::json([
            'garantias' => json_encode($garantiasPossiveis),
        ]);

laravel 5.2 anyone? thanks

0 likes
1 reply
zachleigh's avatar
Level 47

I think you are double encoding the json. Does this work?

Response::json([
            'garantias' => $garantiasPossiveis,
        ]);
1 like

Please or to participate in this conversation.