How to receive a json in Controller and pass to Object array

Asked

Viewed 887 times

3

I am having the following problem, I need to take the Controller filtered objects to export to report. I’m sending by json using Ajax, but I don’t know if object is being sent to Controller,gave a console.log(Answer) and the following appears.

inserir a descrição da imagem aqui

If it’s coming to the controller I don’t know how to get it, if I give decode_json error 500 follows the code:

JS

function ajaxExportar(colaboradores) {
    var token = $("#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 to test for json.

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

        $colaborador=json_encode($json);


         print_r($colaborador);
         die();
}

Route:

Route::post('colaborador/exportar', 'Cadastro\ColaboradorController@exportar');
  • try the following: json_decode($json, true); in your controller and instead of die return the value and see in the "network" what value is receiving

  • gave error 500 :jquery-1.10.2.min. js:4 POST http://localhost:8000/contributor/export 500 (Internal Server Error)

  • and on the network gave : json_decode() expects Parameter 1 to be string, array Given

  • right, what happens is that you are receiving the value of Request::input('json') as an array, not as a string

  • Give me a moment I’ll test it here

  • has an example of what you receive in the variable colaboradores? in Function ajaxExportar(collaborators)?

  • another thing, which version of the Laravel you are using?

  • in the view ? onclick="ajaxExportar('{$collaborators}');" I get it from the controller to filter $contributors

  • I’m using the Portable version 5

  • Version 5.1,5.2 ..?

  • version 5.0

Show 6 more comments

2 answers

6

Change your function on Controller to stay that way, test what is printed on console.log of callback success and post here in the comments.

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

Anyway, it looks like your data is being sent to the Controller, so you can interact with them through the 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);
}
  • Was put as an answer what I commented rs? Had an answer with a very similar content, I think the author removed

  • I do not know, I saw no other answer and in the comments of the question it is not, but if it is similar it must be certain hehe

  • 1

    No problem. I commented because I found similar and I thought it could have been put with this post (I didn’t see if you were moderator)

1

found the solution, I came to share with you. Thank you for your 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

}

JS get from view an array 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");
        }
    }
});

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.