1

I have a table like in this image and I want to get the data from it and save it with this ajax function, but it seems it isn't passing data to php. When I return $this->request->data on my php code the console.log() is trigered at the .fail showing several functions, and when I return json_encode($this->request->data) the .done is triggered but console.log() shows an empty array.

Edit: console.log(JSON.stringify(array)) =

[{"SIA_ID":"1070","DESCONTO_CNES":"100,00","VALOR_PAGO":"679,19"}]

What am I doing wrong?

It seems that I can't post images, so here is a link: https://i.stack.imgur.com/Ov0G5.jpg

Sorry about my English, hope you can understand.

$("#modal-btn-salvar-desconto").on("click", function() {        
    var dadosTabela = $("#tabela-estabelecimento").bootstrapTable("getData");
    var array=[];
    $(dadosTabela).each(function(index) {   
        array[index] = {
            "SIA_ID"        : this.ID,
            "DESCONTO_CNES" : $("#modal-valor-desconto").val().replace("R$", ""),
            "VALOR_PAGO"    : this["VALOR_A_PAGAR"]
        };
    });

    console.log(JSON.stringify(array));

    $.ajax({
        url: "ajaxAtualizar",
        type: "POST",
        dataType: "json",
        data: JSON.stringify(array)
    })
    .done(function(data) {     
            var data = JSON.parse(data);
            if (!data.salvou){
                new PNotify({
                    icon: false,
                    text: '<h5>Registro não pôde ser gravado!<h5>',
                    type: 'error'
                });
                return;
            }
            $(".modal-estabelecimento").modal("toggle");
            $("#mensagem-ajax").html("<div class='" + (data.salvou ? "alert alert-secondary fade in" : "alert alert-warning fade in") + "'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>X</button>" + data.mensagem + "</div>");

    })
    .fail( function(data) {
        console.log("FALHOU");
        console.log(data);
        return;
    });
});



public function ajaxAtualizar() {
    $this->layout = "ajax";
    $this->autoRender = false;              

    if ($this->request->is("ajax")) {           
        foreach ($this->request->data as $dados) {
            $dados["desconto_cnes"]     = str_replace(",", ".", str_replace(".", "", $dados["desconto_cnes"]));
            $dados["desconto_rubrica"]  = str_replace(",", ".", str_replace(".", "", $dados["desconto_rubrica"]));
            $dados["valor_pago"]        = str_replace(",", ".", str_replace(".", "", $dados["valor_pago"]));

            $existeId = $this->Pagamento->findBySiaId($dados["sia_id"]);

            if ($existeId) {
                $dados["id"] = $existeId["PagamentoAmbulatoriai"]["id"];
            }                              
        }

        if ($this->Pagamento->saveAll($dados)) {
            return json_encode(array("salvou" => true, "mensagem" => $this->Mensagem->Msgi(7)));
        } else {
            return json_encode(array("salvou" => false, "mensagem" => $this->Mensagem->Msgi(6)));
        }

    }
}

2 Answers2

0

After more than two days stressing out with this problem, a friend just added

contentType: 'application/json',

to the ajax options and things started working. Now my php controller sees what ajax is sending (what wasn't happening).

And another error that i got and is solved is that you need to use lowercase at the index of the arrays i'm sending with ajax, if not cakephp won't be saving with saveAll.

Although everything is working, i still don't know why do i need to use this contentType since datatype is json already. A lot of requests in the code of friends doesn't even have this option and works...

0

For better understanding i have removed some of your code.

Problems:

  • Dont JSON.stringify the array because it will convert it to string and it will not longer posted as array. After that you have to define a key in which the post value will be send so do like this data: {myData:array}
  • No need of $this->layout = "ajax"; and $this->autoRender = false; as we are requesting json dataType it will give us json data. We have to set the data like this $this->set($dataToSend); $this->set('_serialize', true);

After all the code will be somthing like that.

    $(document).ready(function(){
        $.ajax({
            url: "ajaxAtualizar",
            type: "POST",
            dataType: "json",
            data: {myData:array} // Put a key 
        })
            .done(function(data) {
                console.log(data);

            })
            .fail( function(jqXHR, textStatus, errorThrown) { // Change
                console.log("FALHOU");
                console.log(jqXHR.responseText); // Change
                return;
            });
    });





    public function ajaxAtualizar() {

        $dataToSend = [];
        if ($this->request->is("ajax")) {
            if ($this->request->data('myData')) {
                $dataToSend = array("salvou" => true, "mensagem" => 'Found');
            } else {
                $dataToSend = array("salvou" => false, "mensagem" => 'Problem');
            }
        }
        $this->set($dataToSend);
        $this->set('_serialize', true);
    }
Aman Rawat
  • 2,625
  • 1
  • 25
  • 40
  • Thanks, this works too. So, when should i use JSON.stringify ? – Diego Carjan May 04 '17 at 16:36
  • Check this it has done the same error http://stackoverflow.com/questions/40730233/when-to-use-json-stringify-in-an-ajax-call – Aman Rawat May 04 '17 at 16:47
  • now that its working and saving in the database, my problem is with the response, it always go to the .fail. $this->autoRender = false is because there is no view – Diego Carjan May 04 '17 at 17:33
  • @DiegoCarjan Made changes in the code. Check the `fail` block. Check your console the respose. It is going to fail block because your php file is not returning proper json format. It can be because of some `notice or warning` you are getting in your php code. – Aman Rawat May 04 '17 at 17:36
  • It realy was because of a warning. Thank You very much. – Diego Carjan May 04 '17 at 17:55