Combobox dinâmico com cadastro AJAX

1 Comment »

Cara, não é ‘algo comum’, mas achei interessante essa dúvida, e resolvi montar.
Em funcionamento:
http://www.wbruno.co…form-cidade.php

config.inc.php

  1. <?php
  2.  
  3.         header("Content-Type: text/html; charset=ISO-8859-1");
  4.        
  5.         //Evitando cache de arquivo
  6.         header(‘Expires: Mon, 26 Jul 1997 05:00:00 GMT’);
  7.         header(‘Last Modified: ‘. gmdate(‘D, d M Y H:i:s’) .‘ GMT’);
  8.         header(‘Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0′);
  9.         header(‘Pragma: no-cache’);
  10.         header(‘Expires: 0′);
  11.        
  12.        
  13.         session_start();
  14.  
  15.        
  16.  
  17. ///*
  18.         define(‘SERVIDOR’, ‘localhost’);
  19.         define(‘USUARIO’, ‘root’);
  20.         define(‘SENHA’, ‘123′);
  21.         define(‘BANCO’, ‘ajax’);
  22. //*/

init.inc.php

  1. <?php
  2.         define(‘BASE_PATH’, realpath(dirname(__FILE__)).‘/’);
  3.        
  4.         if( !file_exists(BASE_PATH.‘config.inc.php’) )
  5.                 exit(‘Erro config.php nao encontrado’);
  6.         else
  7.                 require_once BASE_PATH.‘config.inc.php’;
  8.                
  9.         class Db
  10.         {
  11.                 private static $instancia;
  12.                
  13.                 private function __construct(){}
  14.                 private static function conecta()
  15.                 {
  16.                         return new mysqli( SERVIDOR, USUARIO, SENHA, BANCO );
  17.                 }
  18.                 public static function pegaConexao()
  19.                 {
  20.                         if ( self::$instancia == null )
  21.                                 self::$instancia = self::conecta();
  22.                         return self::$instancia;
  23.                 }
  24.         }
  25.         function queryCidade( $where=null )
  26.         {
  27.                 $mysqli = Db::pegaConexao();//pegando uma instância da conexão
  28.                 $sql = "SELECT `id` AS `value`, `nome` AS `label` FROM `cidade` {$where}";
  29.                
  30.                 return $mysqli->query( $sql );          
  31.         }
  32.         function comboCidade( $where=null )
  33.         {
  34.                 $query = queryCidade( $where );
  35.                
  36.                 return montaSelect( $query );
  37.         }
  38.         function montaSelect( $query )
  39.         {
  40.                 if( $query->num_rows )
  41.                         while( $dados = $query->fetch_object() )
  42.                                 $opt .= ‘<option value="’.$dados->value.‘">’.$dados->label.‘</option>’."\n";
  43.                 else
  44.                         $opt = ‘<option value="0">Nenhum registro</option>’;
  45.  
  46.                 return $opt;
  47.         }
  48.         function cadastraCidade( $nome )
  49.         {
  50.                 $nome = utf8_decode( $nome );
  51.                 $mysqli = Db::pegaConexao();//pegando uma instância da conexão
  52.                 $sql = "INSERT INTO `cidade`
  53.                        (`id`, `nome`)
  54.                        VALUES (NULL, ‘{$nome}’)";
  55.                        
  56.                 return $mysqli->query( $sql );
  57.         }
  58.         function isPost()
  59.         {
  60.                 if( $_SERVER[‘REQUEST_METHOD’] == ‘POST’ )
  61.                         return true;
  62.         }
  63.         function getPost( $campo )
  64.         {
  65.                 return isset( $_POST[$campo] ) ? filter( $_POST[$campo] ) : ;
  66.         }
  67.         function getGet( $campo )
  68.         {
  69.                 return isset( $_GET[$campo] ) ? filter( $_GET[$campo] ) : ;
  70.         }
  71.         function filter( $var ){
  72.                 if( !get_magic_quotes_gpc() )
  73.                         //$str = mysql_real_escape_string( $var );
  74.                         $str = addslashes( $var );
  75.                 else
  76.                         $str = $var;
  77.                 $str = str_replace( ‘#’, \#, $str );
  78.                 return $str;
  79.         }
  80.         function jsonCidade( $id=null )
  81.         {
  82.                 $where = ( $id ) ? " WHERE `id` = {$id} " : ;
  83.                
  84.                 $where .= ‘ ORDER BY `nome`’;
  85.                 $query = queryCidade( $where );
  86.                
  87.                 $json = ‘ [';
  88.                 if( $query->num_rows > 0 )
  89.                         while( $dados = $query->fetch_object() )
  90.                                 $json .= '{"nome":"'.$dados->label.'","id":"'.$dados->value.'"}, ';
  91.                 else
  92.                         $json .= '{"nome": "Não Encontrado"}';
  93.                                
  94.                 $json .= ']‘;
  95.                
  96.                 return $json;
  97.         }
  98.         function existeCidade( $cidade )
  99.         {
  100.                 $city = utf8_decode( $cidade );
  101.                 $query = queryCidade( " WHERE nome = ‘{$city}’" );
  102.                 if( $query->num_rows )
  103.                         return $city.‘ já existe!’;
  104.                 else
  105.                         return cadastraCidade( $cidade );
  106.         }
  107.  

retorno.php

  1. <?php
  2.         include ‘init.inc.php’;
  3.        
  4.         if( isset($_GET[‘param’]) )
  5.         {
  6.                 echo jsonCidade( getGet(‘param’) );
  7.         }
  8.         if( getPost(‘cidade’) )
  9.         {
  10.                 echo existeCidade( getPost(‘cidade’) );
  11.         }

form-cidade.php

  1. <?php include ‘init.inc.php’; ?>
  2. <html>
  3. <head>
  4.         <title>Formulário de Cadastro</title>
  5.         <meta name="author" content="William Bruno" />
  6.  
  7.         <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  8.        
  9.         <script type="text/javascript" src="jquery-1.4.2.min.js"></script>
  10.         <script type="text/javascript">
  11.         $(document).ready(function(){
  12.                 $("a[rel*='popup']").click(function( e ){
  13.                         e.preventDefault();
  14.                         var param = $(this).attr(‘rel’).split(‘;’);
  15.                        
  16.                         window.open( $(this).attr(‘href’), $(this).attr(‘href’), param[1] );
  17.                 });
  18.         });
  19.         function carregarCombo( param, combo )
  20.         {
  21.                 $("img[src='ico-loading.gif']").show();
  22.                 $.getJSON(
  23.                         ‘retorno.php’,
  24.                         {param: param},
  25.                         function(data){
  26.                                 var option = new Array();
  27.                                
  28.                                 resetaCombo( combo );
  29.                                 $.each(data, function(i, obj){
  30.                                                
  31.                                         option[i] = document.createElement(‘option’);
  32.                                         $( option[i] ).attr( {value : obj.id} );
  33.                                         $( option[i] ).append( obj.nome );
  34.  
  35.                                         $("select[name='"+combo+"']").append( option[i] );
  36.                         });
  37.                         $("img[src='ico-loading.gif']").hide();
  38.                 });
  39.         }
  40.         function resetaCombo( el )
  41.         {
  42.                 $("select[name='"+el+"']").empty();
  43.                 var option = document.createElement(‘option’);                                  
  44.                 $( option ).attr( {value : ‘0′} );
  45.                 $( option ).append( );
  46.                 $("select[name='"+el+"']").append( option );
  47.         }
  48.         </script>
  49. </head>
  50. <body>
  51.         <form action="" method="post">
  52.                 <label>Cidade: <select name="cidade">
  53.                         <option value=""></option>
  54. <?php echo comboCidade(); ?>
  55.                 </select></label>
  56.                 <a href="cadastrar-cidade.php" rel="popup; width=300px, height=150px, top=150px, left=300px;">Cadastrar Cidade</a>
  57.                
  58.                 <img src="ico-loading.gif" alt="" style="display: none;" />
  59.         </form>
  60. </body>
  61. </html>

cadastrar-cidade.php

  1. <?php
  2.         include ‘init.inc.php’;
  3.         $msg = null;
  4.         if( isPost() )
  5.                 $msg = existeCidade( getPost(‘cidade’) ) ? ‘Cadastro efetuado’ : ‘Ocorreu um erro’;
  6. ?>
  7. <html>
  8. <head>
  9.         <title>Formulário de Cadastro</title>
  10.         <meta name="author" content="William Bruno" />
  11.  
  12.         <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  13.        
  14.         <script type="text/javascript" src="jquery-1.4.2.min.js"></script>
  15.         <script type="text/javascript">
  16.         $(document).ready(function(){
  17.                 $("a.voltar").hide();
  18.                 $("input[name='fechar']").click(function(){
  19.                         fechar_pop();
  20.                 });
  21.                 $("input[name='enviar']").click(function(){
  22.                         $("img[src='ico-loading.gif']").show();
  23.                         $( this ).attr({ disabled: ‘disabled’});
  24.                         $("input[name='cidade']").attr({ disabled: ‘disabled’});
  25.                         $.ajax({
  26.                                 type: ‘POST’,
  27.                                 url: ‘retorno.php’,
  28.                                 data: ‘cidade=’+$("input[name='cidade']").val(),
  29.                                 success: function( data ){
  30.                                         if( data!=1 )
  31.                                         {
  32.                                                 $("input[name='enviar'], input[name='cidade']").attr({ disabled: });
  33.                                                 $("input[name='cidade']").val();
  34.                                                 $("input[name='cidade']").focus();
  35.                                                
  36.                                                 $(‘#retorno’).html( data );
  37.                                         }
  38.                                         else
  39.                                                 fechar_pop();
  40.                                 },
  41.                                 complete: function( xhr, status ){
  42.                                         $("img[src='ico-loading.gif']").hide();        
  43.                                 }
  44.                         });
  45.                         return false;
  46.                 });
  47.         });
  48.         function fechar_pop()
  49.         {
  50.                 window.close();
  51.                 if ( window.opener &amp;&amp; !window.opener.closed )
  52.                         window.opener.carregarCombo( , ‘cidade’ );            
  53.         }
  54.         window.onbeforeunload = fechar_pop;
  55.         </script>
  56. </head>
  57. <body>
  58. <?php if( !$msg ){ ?>
  59.         <form action="" method="post">
  60.                 <label>Cidade: <input type="text" name="cidade" /></label>
  61.                 <label><input type="submit" name="enviar" value="Enviar" /></label>
  62.                 <img src="ico-loading.gif" alt="" style="display: none;" />
  63.                 <p id="retorno"></p>
  64.         </form>
  65. <?php } else echo $msg; ?>
  66.         <a href="form-cidade.php" class="voltar">voltar</a>
  67. </body>
  68. </html>

ico-loading.gif
Imagem
http://www.wbruno.co…ico-loading.gif

jquery-1.4.2.min.js
http://code.jquery.c…ry-1.4.2.min.js

Os códigos estão ai e funcionam.

abril 7th 2010 AJAX