Undefined Value - Data Ajax Javascript

Hi all,

I’m two days trying solve this, but I have no success.

I have a page _form.php for my identificacaoEmigrante.php model and a page _form.php for my filiacao.php model.

In identificacaoEmigrante model, I have fields like:

  • IdEmigrante

  • nome

  • idConjuge

  • nomeConjuge

  • idFiliacao (FK)

and in filiacao model, I have fields like:

  • idFiliacao (PK)

  • nomeMae

  • nomePai

From this, I wanna save the identificacaoEmigrante _form in $_SESSION variables for after get these values in other pages.

I have an interface like this:

5535

Screenshot 2014-05-08 11.52.41.png

When I click on the button with label: "Adicionar nova filiacao", I wanna go to the filiacao _form and fill that form and

when I come back, I want that identificacaoEmigrante _form be filled with previously entered data. IE, I’m filling identificacaoEmigrante _form and filiacao don’t exists yet, so, I need click on button “adicionar nova filiacao” and call filiacao _form through onClick of TbButton event and fill that fields. When I come back from the filiacao _form, I wanna that fields of identificacaoEmigrante _form be filled with the $_SESSION variables.

My identificacaoEmigrante _form.php:




<div class="form container">


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

	'id'=>'identificacao-emigrante-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'=>false,

)); ?>


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


<div class="container">

	<div class="row">

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

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

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

	</div>


	<div class="row">

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

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

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

	</div>


	<div class="row">

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

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

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

	</div>


	<div class="row">

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

		<?php echo $form->textField($model,'idConj',array('size'=>10,'maxlength'=>10)); ?>

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

	</div>


	<div class="row">

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

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

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

	</div>


	<div class="row">

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

        <?php

            if ($model->isNewRecord) {

                $this->widget('bootstrap.widgets.TbSelect2', array(

                       'model' => $modelFiliacao,

                       'attribute' => 'idFiliacao', //'id' CAMPO A BUSCAR

                       'data' => CHtml::listData($modelFiliacao->findAll(), 'idFiliacao', 'nomePai', 'nomeMae'),

                       'htmlOptions' => array('placeholder' => 'Selecione a Filiação',),

                       )); //listData($modelDESEJADO->findAll(), 'CAMPO A SER MODIFICADO', 'CAMPO A MOSTRAR NO COMBOBOX')

            } else if (!$model->isNewRecord) {

                

                $qry = "SELECT filiacao.idFiliacao, nomePai, nomeMae from filiacao, identificacaoEmigrante where filiacao.idFiliacao = identificacaoEmigrante.idFiliacao";

                

                $result = Yii::app()->db->createCommand($qry)->queryAll();

                $data=CHtml::listData($result, 'idFiliacao', 'nomePai', 'nomeMae');

                

                $this->widget('bootstrap.widgets.TbSelect2', array(

                       'model' => $model,

                       'attribute' => 'idFiliacao', //'id' CAMPO A BUSCAR

                       'data' => CHtml::listData($modelFiliacao->findAll(), 'idFiliacao', 'nomePai', 'nomeMae'),

                       'htmlOptions' => array(

                                              'options' => $data,

                                              ),

                       ));

            }

        ?>


        <?php

            $this->widget(

                  'bootstrap.widgets.TbButton',

                  array(

                        'type' => 'primary',

                        'buttonType' => 'ajaxLink',

                        'label' => 'Adicionar nova Filiação',

                        'htmlOptions'=> array(

                            'onClick'=> 'saveSession()',

                        )

                  ));

        ?>


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

	</div>

    <div class="row">

        <?php

            $this->widget(

                  'bootstrap.widgets.TbButton',

                  array(

                        'type' => 'primary',

                        'buttonType' => 'submit',

                        'label' => 'OK',

                        )

                  );

        ?>

    </div>

</div>

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


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



My siteController.php:




    ...

    public function actionMyActionName() {

        Yii::app()->session['idE'] = $_POST['idE'];

        echo json_encode(array("ide"=>$_POST['idE']));

    }

    ...



My Javascript (a.js) code:




function saveSession() {

    $.ajax({

        type: "POST",

        //url: "/museu_emigracao/index.php?r=site/savesession",

        url: '/museu_emigracao/index.php?r=site/myActionName',

        data: {

            idE : $("#idE").val()

        },

        success: function (data) {

            console.log(data.idE);

        },

        error: function (data) {

          alert(data + 'erro');

        },

        dataType: null

    });

}



I’ve tested dataType: JSON and others like “text”, but my code doesn’t return nothing, therefore a null value should be correct.

My code is testing just idEmigrante field now, but without success.

The data.idE return undefined, but in chrome’s debug, it appears with the value (idE: 123).

5536

Screenshot 2014-05-08 13.13.25.png

Any suggestions?

Thanks.

Instead or trying to do this with JavaScript, is it an option to load the $_SESSION values into the model attributes? And then show the form? If I understand your situation correct, that’s how I would do this.




$model = new IdentificacaoEmigrante;

$model->nome = $_SESSION['nome'];


// etc. etc.


$this->render('create',array('model'=>$model,));




Thanks for your answer, but I have do this in an event of a button. How I do this?

In my code, I call saveSession() function that requests an url for do this.

This url is my actionMyActionName() in siteController.php

What is happening here is that the idE: don’t received the value of my input of the form.

Where is $("#idE").val() suppose to come from? I don’t see a field with id=“idE”?

edit: sorry overlooked it, see where it is now.

And of course are you sure the new action is declaired in the accessRules()?

The value is posted as Google Chrome shows. Hard to say why else it would not get there.

My idE is id of an input, how show this line:


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

Each new action should be declared in accessRules?

My action is in principal controller, called siteController.php:




    ...

    public function actionMyActionName() {

        Yii::app()->session['idE'] = $_POST['idE'];

        echo json_encode(array("ide"=>$_POST['idE']));

    }

    ...



I don’t know if I’m correct, but I think so.

After, I would do this for others models that I have.

In my identificacaoEmigranteController.php I have:




	public function accessRules()

	{

		return array(

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

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

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

			),

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

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

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

			),

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

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

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

			),

			array('deny',  // deny all users

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

			),

		);

	}



Yes, you must declaire every action in the accesrules, else it cannot be accessed. This is a beautiful way of security by Yii.

Read the Doc for the details (* = all users, @ = authenticated users etc.), but in your case this should work:




        public function accessRules()

        {

                return array(

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

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

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

                        ),

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

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

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

                        ),

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

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

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

                        ),

                        array('deny',  // deny all users

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

                        ),

                );

        }



Oh, and you only have to add the new action to the accessRules of the controller this action is in, but I guess you already got that.

Ok, I get it, but still didn’t work, even putting in acessRules().

I have read about “undefined” value on js script and maybe I getting this error because the idE isn’t submitted in a POST request to load the page.

Maybe the error is in use just alert() function for the undefined value and don’t do nothing with it.

And now I ask: the input value (idE) really should appear in the alert(data.idE) when I click the TbButton?

I’m a bit confused now!

On success: If I call window.location instead of alert(), the requested page is accessed, but I don’t know if “idE” is with correct value or not!

Anyone help me?

Hi,

I’ve kinda rebuild it and it seems to work.

When I use: console.log(data);

The response is:

{"ide":"26"}

And when I use:

var parsed = JSON.parse(data);

console.log(parsed.ide);

The response is 26.

26 is in my case the id of the model I used to test it.

If you don’t get any results, you have to check if your url: is correct.

Keep on debugging :D

Hi,

I came back to report that I solved the problem a while ago.

I modified the form of resolve the problem, but the Ajax always returns success.

Thanks for help!