How to get a json on Controller and pass to array object

3

I'm having the following problem, I need to get the filtered objects in the Controller to export to report. I'm sending json using Ajax, but I do not know if the object is being sent to Controller, I gave a console.log (response) and the following appears.

Ifyou'regettingintothecontroller,Idonotknowhowtogetit,ifIgivedecode_jsonoferror500followthecode:

JS

functionajaxExportar(colaboradores){vartoken=$("#token").val();
    var json = stringToJson(colaboradores);
    $.ajax({
        url: '/colaborador/exportar',
        type: 'POST',
        method: 'POST',
        dataType: 'json',
        ContentType: 'application/json; charset=utf-8',
        headers: {
            'X-CSRF-TOKEN': token
        },
        data: {
            'json': json,
            '_token': token
        },
        beforeSend: function() {
            $('a').addClass('disabled');
            $("#overlay").faLoading({
                "type": "add",
                "icon": "fa-refresh",
                "status": 'loading',
                "text": false,
                "title": ""
            });
        },
        success: function(response) {
            console.log(response);
            var json = (response);
            $("#overlay").faLoading("remove");
            $('a').removeClass('disabled');
            if (json.error) {
                new PNotify({
                    title: 'Erro!',
                    text: json.error,
                    icon: 'fa fa-warning',
                    type: 'error',
                    styling: 'fontawesome'
                });
            }
        },
        statusCode: {
            //erro de autenticação em caso de logout
            401: function() {
                alert("Necessário fazer login novamente!");
                window.location = "/home";
                //                window.location.reload();
            },
            //erro de servidor
            500: function() {
                alert("Erro servidor");
            },
            //not found
            404: function() {
                alert("Arquivo não encontado");
            }
        }
    })
}

Controller

controller under test to get json.

public function exportar() {
        $json = Request::input('json');

        $colaborador=json_encode($json);


         print_r($colaborador);
         die();
}

Route :

Route::post('colaborador/exportar', 'Cadastro\ColaboradorController@exportar');
    
asked by anonymous 17.10.2018 / 14:39

2 answers

6

Change your role in Controller so that it stays that way, test what is printed on console.log of callback success and post here in comments.

public function exportar(Request $request){
    $dados = $request->except('_token');
    return response()->json($dados);
}

Anyway, it looks like your data is being sent to Controller , so you can interact with them through foreach :

public function exportar(Request $request){
    $dados = $request->except('_token');
    foreach($dados['json'] as $obj){
        echo $obj->id;
        echo $obj->idCargo;
    }
    // return response()->json($dados);
}
    
17.10.2018 / 19:03
0

I found the solution, I came to share with you. Thanks for the help.

Controller

public function exportar() {
  $json = Request::input('json');
    $ids = array();
    for ($i = 0; $i < count($json); $i++) {
        $ids[$i] = $json[$i]['id'];
    }
    $cheque = new Cheque;
    $cheques = $cheque->whereIn('id', $ids)->get(); //aqui posso fazer oqquiser agora que tenho os objetos ja formados

}

I get the view from an array of objects

function ajaxExportar(cheques) {
var token = $("#token").val();
//    var json = stringToJson(colaboradores);
var json = $.parseJSON(cheques);
//    console.log(json);
$.ajax({
    url: '/cheques/exportar',
    type: 'POST',
    method: 'POST',
    dataType: 'text',
    ContentType: 'text',
    headers: {'X-CSRF-TOKEN': token},
    data: {'json': json, '_token': token},
    beforeSend: function () {
        $('a').addClass('disabled');
        $("#overlay").faLoading({
            "type": "add",
            "icon": "fa-refresh",
            "status": 'loading',
            "text": false,
            "title": ""
        });
    },
    success: function (response) {
        var json = $.parseJSON(response);
        var a = document.createElement("a");
        a.href = json.file;
        a.download = json.name;
        document.body.appendChild(a);
        a.click();
        a.remove();
        $("#overlay").faLoading("remove");
        $('a').removeClass('disabled');
        if (json.error) {
            new PNotify({
                title: 'Erro!',
                text: json.error,
                icon: 'fa fa-warning',
                type: 'error',
                styling: 'fontawesome'
            });
        }
    },
    statusCode: {
        //erro de autenticação em caso de logout
        401: function () {
            alert("Necessário fazer login novamente!");
            window.location = "/home";
 //                window.location.reload();
        },
        //erro de servidor
        500: function () {
            alert("Erro servidor");
        },
        //not found
        404: function () {
            alert("Arquivo não encontado");
        }
    }
});

}

    
17.10.2018 / 21:26