Return Json PHP to Ajax

Asked

Viewed 594 times

3

Next I have a variable in php client. printing :

   [{"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 catch 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');
        }
    }); 
});

He’s just printing out the latest information from php client.:

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

I imagine because it is a Json, it will only take the last information, but there is some way I can get all in the Json format?

1 answer

7


The problem has nothing to do with AJAX or JSON, it is an error in the logic used. Your code is zeroing out the variable html inside the loop every time.

Pass the html = "" out of the loop, so:

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>';                   
}
  • That’s right, thank you!

Browser other questions tagged

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