[Solucionado] Necesito Ayuda Con Ajax En Un Formulario

Hace días hice un post parecido pero mas complicado, hoy hago la pregunta un poco mas simplificada espero me puedan ayudar

Tengo un formulario para registrar personas, necesito que al ingresar el número de cédula y quitar el foco en ese campo de texto buscar en la base de datos si existe esa persona y cargar la información a los campos de texto nombre, apellidos, dirección y edad de la persona con esa cédula .

Aquí está el código del formulario, soy nuevo en Yii, disculpen por tantas molestias.




<?php

/* @var $this SolicitantesController */

/* @var $model Solicitantes */

/* @var $form CActiveForm */

?>


<div class="form">


<?php $form=$this->beginWidget('CActiveForm', array(

        'id'=>'solicitantes-form',

        // Please note: When you enable ajax validation, make sure the corresponding

        // controller action is handling ajax validation correctly.

        // There is a call to performAjaxValidation() commented in generated controller code.

        // See class documentation of CActiveForm for details on this.

        'enableAjaxValidation'=>true,

)); ?>


        <p class="note">Campos con <span class="required">*</span> son Obligatorios.</p>


        <?php echo $form->errorSummary($model); ?>


        <div class="row">

                <?php echo $form->labelEx($model,'cedula'); ?>

                <?php echo $form->textField($model,'cedula',array('size'=>12,'maxlength'=>12, 'id'=>'cedula')); ?>

                <?php echo $form->error($model,'cedula'); ?>

        </div>


        <div class="row">

                <?php echo $form->labelEx($model,'nombre'); ?>

                <?php echo $form->textField($model,'nombre',array('size'=>60,'maxlength'=>100, 'id'=>'nombre')); ?>

                <?php echo $form->error($model,'nombre'); ?>

        </div>


        <div class="row">

                <?php echo $form->labelEx($model,'apellido'); ?>

                <?php echo $form->textField($model,'apellido',array('size'=>60,'maxlength'=>100, 'id'=>'apellido')); ?>

                <?php echo $form->error($model,'apellido'); ?>

        </div>


        <div class="row">

                <?php echo $form->labelEx($model,'edad'); ?>

                <?php echo $form->textField($model,'edad',array('id'=>'edad')); ?>

                <?php echo $form->error($model,'edad'); ?>

        </div>


        <div class="row">

                <?php echo $form->labelEx($model,'direccion'); ?>

                <?php echo $form->textField($model,'direccion',array('size'=>60,'maxlength'=>255, 'id'=>'direccion')); ?>

                <?php echo $form->error($model,'direccion'); ?>

        </div>


        <div class="row buttons">

                <?php echo CHtml::submitButton($model->isNewRecord ? 'Crear' : 'Guardar'); ?>

        </div>


<?php $this->endWidget(); ?>


</div>



Hola Miguel,

Para este tipo de cosas es necesario agregar un evento "blur" al campo cédula.

De modo que en un javascript (que puede ser un archivo o anexarse al final de la vista (personalmente prefiero el archivo) ), se coloque algo como:




$('#Solicitantes_cedula').on('blur', function(){ // Si desea un botón, entonces colocar "click" en lugar de "blur", y modificar el "selector" respectivamente con el del botón

    // Código para recargar usando los nuevos parámetros, o en su defecto, el código por ajax para cargar los datos reibidos

}



Saludos, éxitos y bendiciones.

muchas gracias eso ya lo tengo en cuenta, lo que quisiera saber es de si casualidad alguien en el foro tiene el código de ese código javascript o ajax porque lo he buscado por todas partes y no lo encuentro. Y no tengo los conocimientos de javascript o ajax suficientes para realizarlo

Buenas.

Lo del evento ya te lo puso robregonm. Lo que tienes que hacer sería algo parecido a esto:




$.ajax({

     url: "/rutaAplicacion/index.php?r=nombreAccion/existePersona",

     data: {'cedula' : 'valor de tu caja de texto cedula'},

     type: "post",

     success: function(data){

                             // AQUÍ POR EJEMPLO RECUPERAS UN ARRAY CON LOS DATOS DE 

                             // LA PERSONA O NULL SI NO HAY DATOS. ENTONCES COMPRUEBAS 

                             // SI "data" ES NULL. SI NO LO ES, RELLENAS TUS CONTROLES 

                             // CON LOS DATOS DEL ARRAY Y LISTO.

                            }

}); 



Esto lo que hará será enviarte una petición a tu controlador para que se lance la acción existePersona (en donde recogerás la "cedula" enviada, recuperarás los datos para la persona, si los hay, y los devolverás).

Un saludo.

muchas gracias a robregonm y a lagogz eso ya lo intente varias veces pero me resulta el siguiente problema cuando quiero devolver los datos desde el action en el controlador hasta el formulario no lo hace, si conocen alguna forma de hacerlo que sea la correcta en yii porfavor diganmela, si quieren coloco la forma en que lo he hecho para que lo vean?

Y como te vamos a ayudar si no nos muestras como devuelves los datos desde tu controlador?

En tu controlador deberías tener algo así:




$datos = Yii::app()->db->createCommand(

                             "SELECT 

                                   tusCampos 

                              FROM

                                   tuTabla  

                              WHERE 

                                   tusCondiciones

                              ORDER BY 

                                   tuOrden

                              ASC")->queryAll();

        

echo(($datos)?json_encode($datos):'');



Un saludo.

Y como te vamos a ayudar si no nos muestras como devuelves los datos desde tu controlador?

En tu controlador deberías tener algo así:




if($_POST['cedula'])

     $cedula = $_POST['cedula'];

else

     $cedula = -1; 


$datos = Yii::app()->db->createCommand(

                             "SELECT 

                                   tusCampos 

                              FROM

                                   tuTabla  

                              WHERE 

                                   tusCondiciones

                              ORDER BY 

                                   tuOrden

")->queryAll();

        

echo(($datos)?json_encode($datos):'');



O algo parecido, dependiendo d como quieras tratar y recuperar los datos.

Un saludo.

No te molestes :( no lo había mostrado porque lo hice varias veces y como no me salio lo borre, pero iba a hacerlo otra vez para enviárselos probare con el que tu me enviaste que es muy diferente al que yo habia hecho jajajaja aun no soy muy conocedor de yii :P

Bueno gracias a lo que me explicaron robregonm y a lagogz logre aplicarlo al sistema el formulario quedo de la siguiente manera:

PD: aun no se que debo colocar en el function(data) para recuperar los datos desde el controlador, hice un intento de hacer un codigo, si pudiesen ayudarme con eso y disculpen las molestias. Se me ha hecho un poco difícil trabajar con ajax en yii. Otro detalle es que en la url en la function de ajax puse el nombre del controlador / el nombre de la acción, eso es correcto o esta mal?




<?php

/* @var $this SolicitantesController */

/* @var $model Solicitantes */

/* @var $form CActiveForm */

?>


<div class="form">


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'solicitantes-form',

	// Please note: When you enable ajax validation, make sure the corresponding

	// controller action is handling ajax validation correctly.

	// There is a call to performAjaxValidation() commented in generated controller code.

	// See class documentation of CActiveForm for details on this.

	'enableAjaxValidation'=>true,

)); ?>


	<p class="note">Campos con <span class="required">*</span> son Obligatorios.</p>


	<?php echo $form->errorSummary($model); ?>


	<div class="row">

		<?php echo $form->labelEx($model,'cedula'); ?>

		<?php echo $form->textField($model,'cedula',array('size'=>12,'maxlength'=>12, 'id'=>'cedula')); ?>

		<?php echo $form->error($model,'cedula'); ?>

	</div>

    <script>

    $('#cedula').on('blur', function(){

		$.ajax({

     		url: "solicitantes/existePersona",

     		data: {'cedula' : $('#cedula').val()},

     		type: "post",

     		success: function(data){

				// AQUÍ POR EJEMPLO RECUPERAS UN ARRAY CON LOS DATOS DE 

				// LA PERSONA O NULL SI NO HAY DATOS. ENTONCES COMPRUEBAS 

				// SI "data" ES NULL. SI NO LO ES, RELLENAS TUS CONTROLES 

				// CON LOS DATOS DEL ARRAY Y LISTO.

                if (data == null)

                alert("La persona no existe");

                else

                $('#nombre').val() = data.nombre;

                $('#apellido').val() = data.apellido;

			}

		}); 

	}

	</script>

	<div class="row">

		<?php echo $form->labelEx($model,'nombre'); ?>

		<?php echo $form->textField($model,'nombre',array('size'=>60,'maxlength'=>100, 'id'=>'nombre')); ?>

		<?php echo $form->error($model,'nombre'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'apellido'); ?>

		<?php echo $form->textField($model,'apellido',array('size'=>60,'maxlength'=>100)); ?>

		<?php echo $form->error($model,'apellido'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'edad'); ?>

		<?php echo $form->textField($model,'edad'); ?>

		<?php echo $form->error($model,'edad'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'direccion'); ?>

		<?php echo $form->textField($model,'direccion',array('size'=>60,'maxlength'=>255)); ?>

		<?php echo $form->error($model,'direccion'); ?>

	</div>


	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Crear' : 'Guardar'); ?>

	</div>


<?php $this->endWidget(); ?>


</div><!-- form -->



El controlador me quedo asi:




<?php


class SolicitantesController extends Controller

{

	/**

	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

	 * using two-column layout. See 'protected/views/layouts/column2.php'.

	 */

	public $layout='//layouts/column2';


	/**

	 * @return array action filters

	 */

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

			'postOnly + delete', // we only allow deletion via POST request

		);

	}


	/**

	 * Specifies the access control rules.

	 * This method is used by the 'accessControl' filter.

	 * @return array access control rules

	 */

	public function accessRules()

	{

		return array(

			array('allow',  // allow all users to perform 'index' and 'view' actions

				'actions'=>array('index','view', 'ExistePersona'),

				'users'=>array('*'),

			),

			array('allow', // allow authenticated user to perform 'create' and 'update' actions

				'actions'=>array('create','update', 'ExistePersona'),

				'users'=>array('@'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete', 'ExistePersona'),

				'users'=>array('admin'),

			),

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	/**

	 * Displays a particular model.

	 * @param integer $id the ID of the model to be displayed

	 */

	public function actionView($id)

	{

		$this->render('view',array(

			'model'=>$this->loadModel($id),

		));

	}


	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

	{

		$model=new Solicitantes;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Solicitantes']))

		{

			$model->attributes=$_POST['Solicitantes'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->cedula));

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}


	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 * @param integer $id the ID of the model to be updated

	 */

	public function actionUpdate($id)

	{

		$model=$this->loadModel($id);


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Solicitantes']))

		{

			$model->attributes=$_POST['Solicitantes'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->cedula));

		}


		$this->render('update',array(

			'model'=>$model,

		));

	}


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'admin' page.

	 * @param integer $id the ID of the model to be deleted

	 */

	public function actionDelete($id)

	{

		$this->loadModel($id)->delete();


		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

		if(!isset($_GET['ajax']))

			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

	}


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('Solicitantes');

		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new Solicitantes('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['Solicitantes']))

			$model->attributes=$_GET['Solicitantes'];


		$this->render('admin',array(

			'model'=>$model,

		));

	}


	/**

	 * Returns the data model based on the primary key given in the GET variable.

	 * If the data model is not found, an HTTP exception will be raised.

	 * @param integer $id the ID of the model to be loaded

	 * @return Solicitantes the loaded model

	 * @throws CHttpException

	 */

	public function loadModel($id)

	{

		$model=Solicitantes::model()->findByPk($id);

		if($model===null)

			throw new CHttpException(404,'La pagina solicitada no existe.');

		return $model;

	}


	/**

	 * Performs the AJAX validation.

	 * @param Solicitantes $model the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='solicitantes-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}

	}

	

	public function actionExistePersona ()

	{

		if($_POST['cedula'])

     		$cedula = $_POST['cedula'];

		else

     		$cedula = -1; 

		

		$datos = Yii::app()->db->createCommand("SELECT nombre, apellido, sexo, edad, direccion FROM solicitantes WHERE cedula = $cedula")->queryAll();

        

		echo(($datos)?json_encode($datos):'');

	}

}




PD: el WHERE de la consulta quiero comparar el campo que se llama cédula en la tabla solicitantes con la cédula que escribí, lo hice bien comparandolo con $cedula?

Bueno después de varias horas de trabajo con lo que me enviaron robregonm y a lagogz he logrado solucionar mi problema, por supuesto todo gracias a ellos que hicieron la mayor parte yo solo corregí algunos detalles e hice un pequeño código.

Como he notado que ese código no se consigue en ninguna parte en Internet, ni en ingles ni en español voy a dejarlo aquí tal vez a alguien le sirva.

Primero el código del _form




<?php

/* @var $this SolicitantesController */

/* @var $model Solicitantes */

/* @var $form CActiveForm */

?>


<div class="form">


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'solicitantes-form',

	// Please note: When you enable ajax validation, make sure the corresponding

	// controller action is handling ajax validation correctly.

	// There is a call to performAjaxValidation() commented in generated controller code.

	// See class documentation of CActiveForm for details on this.

	'enableAjaxValidation'=>true,

)); ?>


	<p class="note">Campos con <span class="required">*</span> son Obligatorios.</p>


	<?php echo $form->errorSummary($model); ?>


	<div class="row">

		<?php echo $form->labelEx($model,'usuarios_id'); ?>

		<?php echo $form->textField($model,'usuarios_id',array('size'=>60,'maxlength'=>100)); ?>

		<?php echo $form->error($model,'usuarios_id'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'circuitos_id'); ?>

		<?php echo $form->textField($model,'circuitos_id',array('size'=>60,'maxlength'=>100)); ?>

		<?php echo $form->error($model,'circuitos_id'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'cedula'); ?>

		<?php echo $form->textField($model,'cedula',array('size'=>12,'maxlength'=>12, 'id'=>'cedula')); ?>

		<?php echo $form->error($model,'cedula'); ?>

	</div>

    

    <script>

    $('#cedula').on('blur', function(){

		$.ajax({

     		url: <?php echo "'".CController::createUrl('solicitantes/ExistePersona')."'"; ?>,

     		data: {'cedula' : $('#cedula').val()},

     		type: "post",

     		success: function(data){

				if (data == 0){

					alert("No existe la persona");}

				else{

				var retrievedJSON = data;

				var array = JSON.parse(retrievedJSON);

				nombre.value = array[0].nombre;

				nombre.disabled = true;

				apellido.value = array[0].apellido;

				apellido.disabled = true;

				nacimiento.value = array[0].nacimiento;

				nacimiento.disabled = true;

				edad.value = array[0].edad;

				edad.disabled = true;

				if  (array[0].sexo ==1){

				sexo.value = "Masculino";}

				else{

				sexo.value = "Femenino";}

				sexo.disabled = true;

				direccion.value = array[0].direccion;

				direccion.disabled = true;

				numerocasa.value = array[0].numerocasa;

				numerocasa.disabled = true;

				telefono.value = array[0].telefono;

				telefono.disabled = true;

				email.value = array[0].email;

				email.disabled = true;

				}

			}

		});

	})

</script>

    

	<div class="row">

		<?php echo $form->labelEx($model,'nombre'); ?>

		<?php echo $form->textField($model,'nombre',array('size'=>60,'maxlength'=>100, 'id'=>'nombre')); ?>

		<?php echo $form->error($model,'nombre'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'apellido'); ?>

		<?php echo $form->textField($model,'apellido',array('size'=>60,'maxlength'=>100, 'id'=>'apellido')); ?>

		<?php echo $form->error($model,'apellido'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'nacimiento'); ?>

		<?php echo $form->textField($model,'nacimiento', array ('id'=>'nacimiento')); ?>

		<?php echo $form->error($model,'nacimiento'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'edad'); ?>

		<?php echo $form->textField($model,'edad', array ('id'=>'edad')); ?>

		<?php echo $form->error($model,'edad'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'sexo'); ?>

		<?php echo $form->textField($model,'sexo', array ('id'=>'sexo')); ?>

		<?php echo $form->error($model,'sexo'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'direccion'); ?>

		<?php echo $form->textField($model,'direccion',array('size'=>60,'maxlength'=>255, 'id'=>'direccion')); ?>

		<?php echo $form->error($model,'direccion'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'numero casa'); ?>

		<?php echo $form->textField($model,'numerocasa',array('size'=>15,'maxlength'=>15, 'id'=>'numerocasa')); ?>

		<?php echo $form->error($model,'numerocasa'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'telefono'); ?>

		<?php echo $form->textField($model,'telefono',array('size'=>15,'maxlength'=>12, 'id'=>'telefono')); ?>

		<?php echo $form->error($model,'telefono'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'email'); ?>

		<?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>255, 'id'=>'email')); ?>

		<?php echo $form->error($model,'email'); ?>

	</div>


	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Crear' : 'Guardar'); ?>

	</div>


<?php $this->endWidget(); ?>


</div><!-- form -->



el codigo del controlador es el siguiente




<?php


class SolicitantesController extends Controller

{

	/**

	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

	 * using two-column layout. See 'protected/views/layouts/column2.php'.

	 */

	public $layout='//layouts/column2';


	/**

	 * @return array action filters

	 */

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

			'postOnly + delete', // we only allow deletion via POST request

		);

	}


	/**

	 * Specifies the access control rules.

	 * This method is used by the 'accessControl' filter.

	 * @return array access control rules

	 */

	public function accessRules()

	{

		return array(

			array('allow',  // allow all users to perform 'index' and 'view' actions

				'actions'=>array('index','view', 'existepersona', 'obtenerhora'),

				'users'=>array('*'),

			),

			array('allow', // allow authenticated user to perform 'create' and 'update' actions

				'actions'=>array('create','update', 'existepersona', 'obtenerhora'),

				'users'=>array('@'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete', 'existepersona', 'obtenerhora'),

				'users'=>array('admin'),

			),

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	/**

	 * Displays a particular model.

	 * @param integer $id the ID of the model to be displayed

	 */

	public function actionView($id)

	{

		$this->render('view',array(

			'model'=>$this->loadModel($id),

		));

	}


	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

	{

		$model=new Solicitantes;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Solicitantes']))

		{

			$model->attributes=$_POST['Solicitantes'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->cedula));

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}


	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 * @param integer $id the ID of the model to be updated

	 */

	public function actionUpdate($id)

	{

		$model=$this->loadModel($id);


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Solicitantes']))

		{

			$model->attributes=$_POST['Solicitantes'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->cedula));

		}


		$this->render('update',array(

			'model'=>$model,

		));

	}


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'admin' page.

	 * @param integer $id the ID of the model to be deleted

	 */

	public function actionDelete($id)

	{

		$this->loadModel($id)->delete();


		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

		if(!isset($_GET['ajax']))

			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

	}


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('Solicitantes');

		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new Solicitantes('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['Solicitantes']))

			$model->attributes=$_GET['Solicitantes'];


		$this->render('admin',array(

			'model'=>$model,

		));

	}


	/**

	 * Returns the data model based on the primary key given in the GET variable.

	 * If the data model is not found, an HTTP exception will be raised.

	 * @param integer $id the ID of the model to be loaded

	 * @return Solicitantes the loaded model

	 * @throws CHttpException

	 */

	public function loadModel($id)

	{

		$model=Solicitantes::model()->findByPk($id);

		if($model===null)

			throw new CHttpException(404,'La pagina solicitada no existe.');

		return $model;

	}


	/**

	 * Performs the AJAX validation.

	 * @param Solicitantes $model the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='solicitantes-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}

	}

	

	public function actionExistePersona ()

	{

		if($_POST['cedula']){

     		$cedula = $_POST['cedula'];

			

		$datos = Yii::app()->db->createCommand("SELECT nombre, apellido, nacimiento, edad, sexo, direccion, numerocasa, telefono, email FROM solicitantes WHERE cedula = ".$cedula)->queryAll();

			

		echo(($datos)?json_encode($datos):'');}

		

		else{

     		$datos = 0; 

		echo(($datos)?json_encode($datos):''); }

        

	}

}




Me alegro de que lo solucionaras.

Un saludo.