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

Suggest AJAX – jQuery – php/Mysql

14 Comments »

Resolvi brincar um pouquinho aqui..

<html>
<head>
<title>Suggest</title>
<style type="text/css">
* {
        margin: 0;
        padding: 0;
        list-style: none;
        border: none;
}
form {
        width: 400px;
        margin: 0 auto;
}
form label {
        display: block;
}
form label input {
        margin: 2px;
        padding: 2px;
        border: 1px solid #000;
}
.suggest {
        position: relative;
}
.suggest input {
        width: 250px;
}
#suggest {
        position: absolute;
        top: 22px;
        right: 64px;
        background-color: #fff;
        width: 248px;
        text-align: left;
        border: 1px solid #000;
}
#suggest li {
        margin: 2px;
}
#suggest a {
        display: block;
        color: #000;
        text-decoration: none;
}
#suggest a:hover {
        background: #eee;
        text-decoration: underline;
        color: #f00;
}

</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
        $(document).ready(function(){
                $("input[name='suggest']").keyup(function(){
                        createList('.suggest');
                        $.ajax({
                                type: "GET",//apenas pra ficar mais fácil de debugar, pode mudar para POST depois
                                url: "function.php",
                                data: "parte="+$(this).val(),
                                success: function( data ){
                                        $("#suggest").html( data );
                                }
                        });
                });

                $("#suggest a").live('click', function( e ){
                        e.preventDefault();
                        var href = $(this).attr('href');
                        var id = href.split('=');

                        $("input[name='id']").val( id[1] );
                        $("input[name='nome']").val( $(this).text() );

                        $("#suggest").remove();
                });
                $("#suggest").mouseout(function(){
                        $("#suggest").remove();
                });
        });
        function createList( el )
        {
                $("#suggest").remove();

                var list = document.createElement('ul');
                list.id = 'suggest';
                $( el ).append( list );
        }
</script>
</head>
<body>
        <form action="" method="post">
                <fieldset>
                        <label class="suggest">Vá digitando: <input type="text" name="suggest" /></label>

                        <label>ID: <input type="text" name="id" /></label>
                        <label>Nome: <input type="text" name="nome" /></label>
                </fieldset>
        </form>
        <p>Procure por: William, B, J..</p>
</body>
</html>

e o sql disso:

--
-- Banco de Dados: `ajax`
--

-- --------------------------------------------------------

--
-- Estrutura da tabela `cliente`
--

CREATE TABLE IF NOT EXISTS `cliente` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `nome` varchar(50) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `cliente_indexnome` (`nome`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 PACK_KEYS=0 AUTO_INCREMENT=7 ;

--
-- Extraindo dados da tabela `cliente`
--

INSERT INTO `cliente` (`id`, `nome`) VALUES
(1, 'Jeovane Reges'),
(2, 'Felipe Gonçalves'),
(3, 'William'),
(4, 'William Bruno'),
(5, 'Bruno'),
(6, 'Bruno Rocha');

function.php

<?php
        header("Content-Type: text/html; charset=ISO-8859-1");

        echo suggest( getGet('parte') );

function suggest( $palavra )
{
        $sql = "SELECT `id`, `nome` FROM `cliente` ";
        if( !empty($palavra) )
                $sql .= "WHERE `nome` LIKE '{$palavra}%'";

        $mysqli = new mysqli( 'localhost','root','123','ajax' );
        $query = $mysqli->query( $sql );
        if( $query->num_rows>0 )
        {
                $li='';
                while( $dados = $query->fetch_object() )
                        $li .= '<li><a href="?id='.$dados->id.'">'.$dados->nome.'</a></li>';
        }
        else
                $li = 'Nenhum cadastro encontrado!';

        return $li;
}
function getGet( $campo ){
        return ( isset($_GET[ $campo ]) ) ? filter( $_GET[ $campo ] ) : null;
}
function filter( $var )
{
        if( !get_magic_quotes_gpc() )
                $str = mysql_real_escape_string( $var );
        else
                $str = $var;
        $str = str_replace( '#', '\#', $str );
        return $str;
}

^_^

Em funcionamento:
http://www.wbruno.co…pts/suggest.php
:natal_happy:

janeiro 8th 2010 AJAX

Combos dependentes AJAX-jQuery

1 Comment »

Boas galera!

Fiz aqui um exemplo do que eu mesmo já procurei muito por ai.
Sou péssimo para explicações, então lá vão os códigos.

Embaixo no script php, eu comentei as linhas caso queria usar a biblioteca mysql, em vez da mysqli(prefira o i, caso MySQL > 4.1)
index.php

<html>
<head>
        <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function(){//inicio o jQuery
                $("select[name='combo1']").change(function(){
                var idCombo1 = $(this).val();//pegando o value do option selecionado
                //alert(idCombo1);//apenas para debugar a variável

                        $.getJSON(//esse método do jQuery, só envia GET
                                'function.inc.php',//script server-side que deverá retornar um objeto jSON
                                {idCombo1: idCombo1},//enviando a variável

                                function(data){
                                //alert(data);//apenas para debugar a variável

                                        var option = new Array();//resetando a variável

                                        resetaCombo('combo2');//resetando o combo
                                        $.each(data, function(i, obj){

                                                option[i] = document.createElement('option');//criando o option
                                                $( option[i] ).attr( {value : obj.id} );//colocando o value no option
                                                $( option[i] ).append( obj.nome );//colocando o 'label'

                                                $("select[name='combo2']").append( option[i] );//jogando um à um os options no próximo combo
                                });
                        });
                });
        });     

        /* função pronta para ser reaproveitada, caso queria adicionar mais combos dependentes */
        function resetaCombo( el )
        {
                $("select[name='"+el+"']").empty();//retira os elementos antigos
                var option = document.createElement('option');
                $( option ).attr( {value : '0'} );
                $( option ).append( 'Escolha' );
                $("select[name='"+el+"']").append( option );
        }
        </script>
</head>
<body>
<form action="" method="post">
        <fieldset>
                <label><select name="combo1">
                        <option value="0">Escolha</option>
                        <option value="1">Item 1</option>
                        <option value="2">Item 2</option>
                        <option value="3">Item 3</option>
                </select></label>

                <label><select name="combo2">
                        <option value="0">Escolha</option>
                </select></label>
        </fieldset>
</form>
</body>
</html>

function.inc.php

<?php
        header("Content-Type: text/html; charset=ISO-8859-1");

        function intGet( $campo ){
                return isset( $_GET[$campo] ) ? (int)$_GET[$campo] : 0;
        }
        function retorno( $id )
        {
                $sql = "SELECT `id`, `nome`
                        FROM `combo2`
                        WHERE `idCombo1` = {$id} ";
                $sql .= "ORDER BY `nome` ";

                $mysqli = new mysqli("localhost", "root", "123", "ajax");
                //$con = mysql_connect('localhost', 'root', '123');
                //mysql_select_db( 'ajax', $con );

                $q = $mysqli->query( $sql );
                //$q = mysql_query( $sql );

                $json = ' [';
                if( $q->num_rows > 0 )
                //if( mysql_num_rows( $q ) > 0 )
                {
                        while( $dados = $q->fetch_object() )
                        //while( $dados = mysql_fetch_assoc( $q ) )
                        {
                                $json .= '{"nome'.$campo.'":"'.$dados->nome.'","id'.$campo.'":"'.$dados->id.'"}, ';
                                //$json .= '{"nome'.$campo.'":"'.$dados['nome'].'","id'.$campo.'":"'.$dados['id'].'"}, ';
                        }
                }
                else
                        $json .= '{"nome'.$campo.'": "Não Encontrado"}';

                $json .= ']';

                return $json;
        }

        echo retorno( intGet('idCombo1') );

Uma forma simples de debugar, é acessando diretamente:
http://localhost/com….php?idCombo1=2

No meu caso, fiz essa pasta ‘combo’, só para organizar as coisas por aqui.

Em funcionamento:

http://www.wbruno.com.br/scripts/combos-dependentes.php

outubro 6th 2009 AJAX