Querying data in PHP using the $ .get json method and listing data in an html

1

I can do the data insertion but I have no idea how to do data selection on a HTML using $.get JSON .

php code

public function Inserir($tabela,$sql){            
     ksort($sql);
     $Campos_nome=  implode('', '', array_keys($sql));
     $Campos_valor= ':'. implode(', :', array_keys($sql));
     $novo=$this->prepare("INSERT INTO $tabela ( '$Campos_nome') VALUES ( $Campos_valor)");
     foreach ($sql as $key => $valor) {
         $novo->bindValue(":$key", $valor);
     }         
     $novo->execute();            
     if($novo->rowCount()>0){
         $novo->setFetchMode(PDO::FETCH_ASSOC);
         $valor=$novo->fetchAll(); 
         print json_encode($valor,JSON_PRETTY_PRINT);
     }            
}//fim

Then I do the serialization of my Form sending the data via POST to my php file. Here is the code:

$("#novo").submit(function(){
    var url = $(this).attr('action');  
    var data = $(this).serialize();

    $.post(url,data,function(data){
        $('#result').append('<div>'+o.nome+'</div>');
        console.log(o.nome);
    });

    return false;
});

How do I return values in tabela or <li> using method $.get ?

Note: I tried to do this using append but it does not work correctly:

function listar(){
  $.get(url,function(data){
     $('#div').append('<div>'+data.nome+'</div>');
     $('#div').append('<div>'+data.email+'</div>');
  )};
}
    
asked by anonymous 28.05.2014 / 11:25

2 answers

1

In PHP filename = json.php

<?php
 ...
 .../*consulta ao banco de dados*/
$rows=array();
while($row = mysql_fetch_assoc($result))
 {
 $rows[]= $row;

}


header('Content-Type: application/json');
echo json_encode($rows);


?>

In Javascript:

  $.getJSON( "json.php", function( json ) {
  var items = [];
  $.each( json, function( key, val ) {
     items.push( "<li id='" + key + "'>" + val + "</li>" );
  });

  $( "<ul/>", {
   "class": "my-new-list",
    html: items.join( "" )
    }).appendTo( "body" );
  });
    
28.05.2014 / 18:27
1

Instead of the name , put date.name , because your return address is date / strong>. Make sure that a json is coming in with json_encode in its PHP and add in your jQuery in the last setting the word 'json' .

$("#novo").submit(function(){
    var url = $(this).attr('action');  
    var data = $(this).serialize();

    $.post(url, data, function (data) {
      $.each(data, function (index, value) {
        $('#result').append('<div>' + value.nome + '</div>');
        $('#result').append('<div>' + value.email + '</div>');
     });
    }, 'json');

    return false;
});
    
28.05.2014 / 15:05