Welcome Guest, Not a member yet? Register   Sign In
Tutorial Ajax Library with jQuery (English/Spanish Version)
#1

[eluser]Unknown[/eluser]
Uno de los inconvenientes mas tediosas de mi paso a CodeIgniter fue la implementacion de Ajax, para todo incluian mucho codigo que hacia de la versatilidad de CodeIgniter un obstaculo, sin embargo basandome en jQuery, pude resolver el problema de la facilidad de una libreria para poder usar Ajax de una manera facil y rapida.

1. Instalacion de los Archivos

En este post, se encuentran los archivos basicos para que empecemos, el archivo zip consta de:

/js/BWGAjax/util.js este es un javascript con los utilitarios necesarios para llenar combos y tablas, esto ha sido basado en el util.js de DWR, a los cuales admiro muchisimo por que esta es un gran archivo de metodos para trabajar apropiadamente con Ajax.
/system/application/libraries/bwgajax.php la cual no es mas que una libreria pequeña para la creacion de nuestros metodos ajax con jQuery.
/system/application/config/config.php el config.php de CodeIgniter ha sido modificado para agregar unos nuevos items para la configuracion de BWGAjax.

Estos archivos deben ser incluidos dentro de nuestro proyecto codeigniter, en el caso del config.php solo deberiamos agregar los nuevos items en tu archivo, los cuales se encuentran al final del archivo iniciando con el comentario Ajax Config.

2. Creacion del Controlador de Ajax

Deberiamos crear un controlador que nos ayude unicamente a ser el contenedor de los metodos de javascript que se van a usar, en este tutorial, lo vamos a usar para los metodos que vayamos a usar.

Inicialmente crearemos un metodo en el controlador llamado js.
Code:
<?
class Ajax extends Controller {
       function Ajax(){
              parent::Controller();
       }

       function js(){
              $this->load->library('bwgajax'); // Cargamos nuestra libreria
              $this->bwgajax->ajax_create();  // Ejecutamos la creacion de los metodos ajax
       }

}
?>

3. Creacion de nuestra vista

Vamos a agregar la js de jQuery, nuestra js de utilidades, y por ultimo el controlador con el metodo /js

Code:
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>BrainWinner Ajax</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">/script>
        <script type="text/javascript" src="<?=base_url()?>js/BWGAjax/util.js"></script>
        <script type="text/javascript" src="<?=base_url()?>index.php/ajax/js"></script>
        <script type="text/javascript">
            
        </script>
    </head>
    <body>
        
    </body>
</html>

Actualmente, no hemos aun configurado nuestros metodos, sin embargo podemos verificar que el BWGAjax esta funcionando ejecutando el controlador y el metodo que hemos realizado actualmente. http://localhost/your_app/index.php/ajax/js, ejecutando esto veriamos:
Code:
//Fabio Arias

Ahora agreguemos a nuestra vista un contenedor para un dato que queremos traer desde BWGAjax.
Code:
<span id="nombre"></span>

Necesitaremos entonces un boton para ejecutar nuestro ajax, y le agregamos el metodo
Code:
enviar()
que tendremos que agregar como evento.
Code:
&lt;input type="button" name="enviar" value="Enviar" onclick="enviar();"&gt;

Code:
&lt;script type="text/javascript"&gt;
            // Metodo Handler del Evento del Boton
            function enviar(){
                     obtenerAjax('Hola Mundo', setNombre);
// obtenerAjax() va a ser nuestro metodo que vamos a crear como ajax, el primer parametro equivale a la data que vamos a enviar, el segundo parametro será el metodo que recogera el response de este metodo.
            }

            function setNombre(val){
                      // Vamos a setear el valor de la respuesta en nuestro <span/> creado con el id nombre
                      BWGUtil.setValue('nombre', val);
            }
&lt;/script&gt;

4. Creacion metodo obtenerAjax en Controlador
Code:
&lt;?
class Ajax extends Controller {
       .....
       .....

       function obtenerAjax(){
                echo $_POST['dato']." desde BWGAjax";
       }

}
?&gt;

5. Agreguemos nuestros metodos Ajax en el config.php
Code:
$config['bwgajax_metodos'][] =  array(
                                    'metodo'    => 'obtenerAjax', // aqui agregamos el nombre del metodo que vamos a crear
                                    'params'    => array(
                                                        'dato'  // Vamos agregar un parametro de entrada llamado dato
                                                        ),
                                    'url'       => 'ajax/obtenerAjax' // y decimos cual es el controlador y metodo
                                );

Volvemos a ejecutar nuestro metodo /js del controlador ajax y vamos a obtener esto:

Code:
//Fabio Arias

function obtenerAjax(dato,function_back){
$.ajax({
                        type: 'POST',
                        url: 'http://localhost/your_app/index.php/ajax/obtenerAjax',
                        data:{dato : dato},
                        success: function_back
                        });
                    }

Bueno ahora ya con esto podemos ejecutar nuestro controlador.

Si todo nos fue bien vamos a obtener al dar clic sobre nuestro boton:

Quote:Hola Mundo desde BWGAjax

Bueno Muchachos espero que esto les ayude, no olviden consultar
@poetablanco
#2

[eluser]Unknown[/eluser]
Fabio asked me to translate his post to english:

Quote:One of the tedious inconvinients of my moving to CodeIgnite was the Ajax implementation, it had a lot of code and made CodeIgniter to lose versatility, but based in jQuery, I could resolve the problem making a library in order to use Ajax in easy and quick way.

1. Files Installation

In this post you can find the basic files, the zip file have inside:

/js/BWGAjax/util.js this is a javascript file with the utilities necessary to fill combos and tables, this was made based in the util.js of DWR, which I like, because of the ease to work propertly with Ajax.
/system/application/libraries/bwgajax.php Is a small library for the creation of the ajax methods(functions) with jQuery.
/system/application/config/config.php Is the config.php of CodeIgniter, this was modified, adding some new items for the configuration of BWGAjax.

These files must be included in our project, in the case of config.php we just have to add the new items in the file, which you can find at the end of the file below the comment Ajax Config.

2. Creating the Ajax Controller

You need to create a new Controller this is going be the container of the methods javascript is going to need.

Create a method in the Controller called js.
Code:
&lt;?
class Ajax extends Controller {
       function Ajax(){
              parent::Controller();
       }

       function js(){
              $this->load->library('bwgajax'); // This loads the library
              $this->bwgajax->ajax_create();  // This calls the creation of ajax methods
       }

}
?&gt;

3. Creating the View

Add the js of jQuery inside the js of utilities, and finally the Controller with the method js/

Code:
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
        &lt;title&gt;BrainWinner Ajax&lt;/title&gt;
        &lt;script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"&gt;/script&gt;
        &lt;script type="text/javascript" src="&lt;?=base_url()?&gt;js/BWGAjax/util.js"&gt;&lt;/script&gt;
        &lt;script type="text/javascript" src="&lt;?=base_url()?&gt;index.php/ajax/js"&gt;&lt;/script&gt;
        &lt;script type="text/javascript"&gt;
            
        &lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        
    &lt;/body&gt;
&lt;/html&gt;
Currently, we havent configured our methods, however we can verify that the BWGAjax is working executing the controller and the method we made. http://localhost/your_app/index.php/ajax/js, calling this, you'll see:
Code:
//Fabio Arias

Now add the view to a container for an information we want to bring from the BWGAjax.
Code:
<span id="nombre"></span>

We need then a button to execute the ajax, and add it the method
Code:
enviar()
that we need to send as an event.

Code:
&lt;input type="button" name="enviar" value="Enviar" onclick="enviar();"&gt;

Code:
&lt;script type="text/javascript"&gt;
            // Method's Handler of the button event
            function enviar(){
                     obtenerAjax('Hola Mundo', setNombre);
// obtenerAjax() Is going to be our Ajax method, the first parameter is the data we're going to send, the second parameter is the method that will capture the response of this method.
            }

            function setNombre(val){
                      // This sets the value of the response in the <span/> created with the id of nombre
                      BWGUtil.setValue('nombre', val);
            }
&lt;/script&gt;

4. Creating the obtenerAjax(obtain Ajax) method in the Controller
Code:
&lt;?
class Ajax extends Controller {
       .....
       .....

       function obtenerAjax(){
                echo $_POST['dato']." desde BWGAjax";
       }

}
?&gt;

5. Adding the Ajax methods in the config.php
Code:
$config['bwgajax_metodos'][] =  array(
                                    'metodo'    => 'obtenerAjax', // Here we add the name we're going to create
                                    'params'    => array(
                                                        'dato'  // We add a parameter called dato                                                        ),
                                    'url'       => 'ajax/obtenerAjax' // And specify the Controller and the method
                                );

Execute again the /js method of the Ajax Contrller and you'll this:

Code:
//Fabio Arias

function obtenerAjax(dato,function_back){
$.ajax({
                        type: 'POST',
                        url: 'http://localhost/your_app/index.php/ajax/obtenerAjax',
                        data:{dato : dato},
                        success: function_back
                        });
                    }

Ok, now with this we can execute our Controller.

If everything is ok, when you click the button you'll see this:

Quote:Hola Mundo desde BWGAjax

To contact me:

@poetablanco

Any questions you can ask me as well.
@foxxor

Bye.
#3

[eluser]electronik_0[/eluser]
Gracias, vamos a probar que tal Big Grin




Theme © iAndrew 2016 - Forum software by © MyBB