Query $.get json and show result

Asked

Viewed 728 times

0

I am sending an array for a query in a Mysql database via $.getJSON and in php I am mounting a table, but I am not being able to return and display this table, how can I do this?

My code that sends the parameters is like this:

         // Gravação e mensagem no retorno do cadastro do comentário
    $(document).ready(function () {
        $("#btnImprimeLista").click(function () {

            var nChecked = new Array();

            $("input[name='check[]']:checked").each(function () {
                nChecked.push(parseInt($(this).val()));
            });

            $.getJSON(
                'imprimetodoslista.php', {
                    list: nChecked
                },
                function (json) {
                console.log(json);
                // Mostrar a tabela no retorno      
                }
            );
        });
    }); 

PHP looks like this:

// Consultando candidados no banco
foreach($checkboxes as $id) {

    mysql_select_db($database_con, $con);
    $query_rsRegistro = "SELECT nome, email, celular, id_municipio, id_uf, dt_nascimento FROM candidato WHERE id_candidato = '$id'";
    $rsRegistro = mysql_query($query_rsRegistro, $con) or die(mysql_error());
    $row_rsRegistro = mysql_fetch_assoc($rsRegistro);
    $totalRows_rsRegistro = mysql_num_rows($rsRegistro);

    $Nome = $row_rsRegistro['nome'];
    $Email = $row_rsRegistro['email'];
    $Celular = $row_rsRegistro['celular'];
    $Municipio = $row_rsRegistro['id_municipio'];
    $UF = $row_rsRegistro['id_uf'];
    $Nascimento = $row_rsRegistro['dt_nascimento'];

    $tabela = "     
     <table width=100%  border=0 cellpadding=2 cellspacing=1>
      <tr>
        <td>Nome</td>
        <td>E-mail</td>
        <td>Celular</td>
        <td>Municipio</td>
        <td>UF</td>
        <td>Nascimento</td>
      </tr>";            
    do {            
      $tabela .= "
      <tr>
        <td>{$Nome}; </td>
        <td>{$Email}; </td>
        <td>{$Celular}; </td>
        <td>{$Municipio};</td>
        <td>{$UF};</td>
        <td>{$Nascimento};</td>     
      </tr>";
    } while ($row_rsRegistro = mysql_fetch_assoc($rsRegistro)); 
    $tabela .= "</table>";  

}

$arr['msg'] = $tabela;      

$arr = array_map('htmlentities',$arr);
echo json_encode($arr); 

1 answer

1


The problem is in the return of the code, you are using the getJSON function, in this case the PHP value should be returned via JSON and not as an HTML.

The way you are using, change the getJSON function to $.get (http://api.jquery.com/jquery.get/) or else return JSON values without HTML passing only the results/array (http://www.php.net/manual/en/function.json-encode.php) so that Javascript can interpret the return.

json_encode($row_rsRegistro);

I hope I’ve helped you.

  • Excellent tip, thanks so much @Marcus V. Nash.

Browser other questions tagged

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