Return Json PHP to Ajax

3

Next I have a variable in client.php that prints:

   [{"CODIGO_CLIENTE":3,"CGC":"78.079.128\/0001-80","RAZAO":"Cliente 2","FANTASIA":"Cliente 2","TELEFONE1":"+99(99)9999-9999"},
    {"CODIGO_CLIENTE":2,"CGC":"14.617.787\/0001-40","RAZAO":"Cliente 1","FANTASIA":"Cliente 1","TELEFONE1":"+99(99)9999-9999"},
    {"CODIGO_CLIENTE":5,"CGC":"54.731.556\/0001-87","RAZAO":"Cliente 3","FANTASIA":"Cliente 3","TELEFONE1":"+99(99)9999-9999"},
    {"CODIGO_CLIENTE":6,"CGC":"55.765.452\/0001-56","RAZAO":"Cliente 4","FANTASIA":"Cliente 4","TELEFONE1":"+99(99)9999-9999"}]

And I try to get Json via Ajax as follows:

    $('#btn-sinc').click(function() {   
    $.ajax({
        type : "POST",
        url : "http://localhost/read/cliente.php",
        crossDomain: true,      
        contentType: "application/json; charset=utf-8",
        dataType: 'json',       
        success : function(responseData, textStatus, jqXHR) {

            for(var i=0; i < responseData.length; i++){
                var html = "";
                    html += '<tr>'; 
                    html += '<td data-label="Cnpj">'+responseData[i].CGC+'</td>';
                    html += '<td data-label="Razão">'+responseData[i].RAZAO+'</td>';                    
                    html += '<td data-label="Fantasia">'+responseData[i].FANTASIA+'</td>';                  
                    html += '<td data-label="Telefone">'+responseData[i].TELEFONE1+'</td>';                          
                    html += '</tr>';                   
            }

            $('.table').html(html);         
        },
        error: function (responseData, textStatus, errorThrown) 
        {
            console.warn(responseData, textStatus, errorThrown);
            alert('Falha');
        }
    }); 
});

It is only printing the latest client.php information:

{"CODIGO_CLIENTE":6,"CGC":"55.765.452\/0001-56","RAZAO":"Cliente 4","FANTASIA":"Cliente 4","TELEFONE1":"+99(99)9999-9999"}

I imagine it's a Json, it will only get the latest info, but is there any way I can get all of them in Json format?

    
asked by anonymous 26.10.2016 / 13:25

1 answer

6

The problem does not have to do with AJAX or JSON, it is an error in the logic used. Your code is zeroing the html variable within the loop every time.

Pass html = "" out of the loop, like this:

var html = "";
for(var i=0; i < responseData.length; i++){
    html += '<tr>'; 
    html += '<td data-label="Cnpj">'+responseData[i].CGC+'</td>';
    html += '<td data-label="Razão">'+responseData[i].RAZAO+'</td>';                    
    html += '<td data-label="Fantasia">'+responseData[i].FANTASIA+'</td>';                  
    html += '<td data-label="Telefone">'+responseData[i].TELEFONE1+'</td>';                           html += '</tr>';                   
}
    
26.10.2016 / 13:27