Update Content With Ajax And Ajax Auto Refresh Div

Hi all,

I'm developing an web page and i would like to add Ajax post option in the index page...

i.e when the user submit the post it will store in the database and i want to display the content below the post form without refreshing the hole page. Or otherwise i want to refresh the content div every 10 sec.

I had already refereed some forum but it doesn’t work… Please anyone help me:(

Hi,

Write your form and don’t use a button for submitting the form , then write a javascript function then serialize the form data and send to server. Validate the code and save it to the database then on ajax success refresh the div you want to display the result.

Reference : jquery serialize

Note at your ajax code data : "Your serialized data"

Cheers!

[font="Comic Sans MS"]Thanks for responding…[/font]

Sorry I’m very new to Yii. so, could you please give some sample demo code or example Arockia Johnson. So that i can able to do the same. :(

Can you please post your sample form code alone?

let me modify here and reply the post

index.php


<div id="forumForm">

	<div id="simple-div">

		<?php echo $this->renderPartial('_uploadStatus', array('model'=>$model)); ?>

	</div>

</div>


<hr style="height: 1px;"/>

<div id="list-of-post" class="list-post">

<?php

	$this->widget('zii.widgets.CListView', array(

		'dataProvider'=>$dataProvider,

		'itemView'=>'_view',

	));

?>

</div>



_uploadStatus.php


<div class="form">

<?php $form=$this->beginWidget('CActiveForm'); ?>

	<?php echo CHtml::errorSummary($model); ?>

	<div class="row">

		<?php echo $form->hiddenField($model,'user_id', array('value'=>Yii::app()->user->id), array('size'=>20,'maxlength'=>20)); ?>

	</div>

	<div class="row">

		<?php echo $form->textArea($model,'content', array('placeholder'=>"What's going on...!", 'class'=>'status-txt-area')); ?>

	</div>

	<div>

		<?php echo CHtml::submitButton('Post', array('id'=>'post-submit-btn', 'disabled'=>'disabled', 'class'=>'post-btn')); ?>

	</div>

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

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

ForumPostController.php


public function actionIndex() {

	$model = new ForumPost;


	if(isset($_POST['ForumPost'])) {

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

		$model->save();

		$this->refresh();

		// $this->redirect(Yii::app()->user->returnUrl);

	}


	$dataProvider=new CActiveDataProvider('ForumPost', array(

						'sort'=>array(

    						'defaultOrder'=>'updated DESC',

  						)

					));

	// $this->rightBar = $this->renderPartial('userProfile',array(''),true);

	// $this->leftBar = $this->renderPartial('reference',array(''),true);

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

}



and i didnt know how to refresh the content div and ajax upload…

instead of using


 CHtml::SubmitButton( )

use


ajaxSubmitButton( )

for submitting the form. for more information refer manuals…

Thanks Ahamed Rifaideen,

if you have any demo code, please share :(

sorry I am using mobile :( so

refer thisthis website to get clear idea about ajax

Ahamed Rifaideen its working but i want to refresh the div every 10 or 15sec. and also I’m providing a Ajax comment option under every new post.?

Hi Follow my steps below…

Create a new action as follows

Step : 1 Create a new view file namely _ForumPost







<div id="list-of-post" class="list-post">

<?php

        $this->widget('zii.widgets.CListView', array(

                'dataProvider'=>$dataProvider,

                'itemView'=>'_view',

        ));

?>

</div>




Step :2 Rewrite your action as follows





public function actionIndex($id=NULL) {

        $model = new ForumPost;


        if(isset($_POST['ForumPost'])) {

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

                $model->save();

                $this->refresh();

                // $this->redirect(Yii::app()->user->returnUrl);

        }


        $dataProvider=new CActiveDataProvider('ForumPost', array(

                                                'sort'=>array(

                                                'defaultOrder'=>'updated DESC',

                                                )

                                        ));

	if(isset($id)){

		$this->renderPartial('_ForumPost',array('dataProvider'=>$dataProvider));

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


	}


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

}




Rewrite your index.php view file as follows





<div id="forumForm">

        <div id="simple-div">

                <?php echo $this->renderPartial('_uploadStatus', array('model'=>$model)); ?>

        </div>

</div>


<hr style="height: 1px;"/>

<div id="list-of-post" class="list-post">

<?php

        Yii::app()->runController('ForumPost/id/true');

?>

</div>



Rewrite your _uploadStatus.php view file as follows





<div class="form">

<?php $form=$this->beginWidget('CActiveForm'); ?>

        <?php echo CHtml::errorSummary($model); ?>

        <div class="row">

                <?php echo $form->hiddenField($model,'user_id', array('value'=>Yii::app()->user->id), array('size'=>20,'maxlength'=>20)); ?>

        </div>

        <div class="row">

                <?php echo $form->textArea($model,'content', array('placeholder'=>"What's going on...!", 'class'=>'status-txt-area')); ?>

        </div>

        <div>

                <?php echo CHtml::Button('SUBMIT',array('onclick'=>'javascript:send();')); ?> 

        </div>

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

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


<script type="text/javascript">

 

function send()

 {

 

   var data=$("#your-form_id").serialize();

 

 

  $.ajax({

   type: 'POST',

    url: '<?php echo Yii::app()->createAbsoluteUrl("ForumPost"); ?>',

   data:data,

success:function(data){

                 jQuery("#list-of-post").load(<?php echo Yii::app()->createAbsoluteUrl("ForumPost/index?id=true"); ?>);

              },

   error: function(data) { // if error occured

         alert("Error occured.please try again");

         alert(data);

    },

 

  dataType:'html'

  });

 

}

 

</script>




Finally write your ajax form submit code at your action…

Cheers!

If works don’t hesitate to press +

thanks for sharing the code S.Arockia Johnson

i have some doubts in the above code. why should we pass the


$id

in the action Index.

and i didn’t get the following code.


<?php

        Yii::app()->runController('ForumPost/id/true');

?>



one more issue is i cant render the _ForumPost.php file in the action index.

Hi ,

In order to render the view partially. As you can see the code if the id is set it will render the view partially and the app ends.

Got your exact output?

Cheers!

I am here to help you!


<script type="text/javascript">

function send() {

	var data=$("#post-form").serialize();

	 alert(data);

		$.ajax({

			type: 'POST',

			url: '<?php echo Yii::app()->createUrl("forumPost/forumUploadStatus"); ?>',

			data:data,

			success:function(data) {

				$("#list-of-post").append(data);

				// jQuery("#list-of-post").load('+<?php echo Yii::app()->createUrl("ForumPost/index"); ?>+');

			},

			error: function(data) { // if error occured

				alert("Error occured.please try again");

				 alert(data);

			},

			dataType:'html'

		});

}

</script>

This is my script to load the post using Ajax. and i want to know what the following line describes ?


jQuery("#list-of-post").load('+<?php echo Yii::app()->createUrl("ForumPost/index"); ?>+');

And the post details are getting in the forumPost/forumUploadStatus action. I don’t know how to fetch the data from controller? please help me :(

Load is shorthand for the ajax call. This line would take whatever is in ForumPost/index and put it in list-of-post. If you need the input from the form to prepare the respons from the controller, you shouldn’t use this here.

Fill in the url of the action that you want to address to process your ajax request.

To post the form input to that action, i would use serializeArray(). That way you get the data as an array in your controller. There you can process the data and prepare any html response. The html you echo will be in the data parameter of the success handler.

You can then use $("#list-of-post").append(data) to add the respons to that element or $("#list-of-post").html(data) to replace the element completely.

Thanks for the help. finally i have modified the view and controller to get the output.

My Controller:

To store the values in the database.


public function actionForumUploadStatus() {

		$model=new ForumPost;

		if(isset($_POST['ForumPost'])){

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

	            $model->save();

		}

	 }

retrieve the data from db:


public function actionForumPostDisplay() {

		$model=new ForumPost;

	 	$dataProvider=new CActiveDataProvider('ForumPost', array(

                                                'sort'=>array(

                                                'defaultOrder'=>'updated DESC',

                                                )));

			$this->renderPartial('_ForumPost',array('dataProvider'=>$dataProvider),false,true);

	 }

View:

_uploadStatus.php


<div class="form">

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

	'id'=>'post-form',

)); ?>

        <?php echo CHtml::errorSummary($model); ?>

        <div class="row">

                <?php echo $form->hiddenField($model,'user_id', array('value'=>Yii::app()->user->id), array('size'=>20,'maxlength'=>20)); ?>

        </div>

        <div class="row">

                <?php echo $form->textArea($model,'content',

                array('placeholder'=>"What's going on...!",

                	  'class'=>'status-txt-area',

                	  'onkeyup'=>'javascript: enableBtn(this.value);')); ?>

        </div>

        <div>

                <?php echo CHtml::htmlButton('Post',array('onclick'=>'javascript: send();', 'id'=> 'post-submit-btn')); ?>

                        </div>

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

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


<script type="text/javascript">


function send() {

	var data=$("#post-form").serialize();


		$.ajax({

			type: 'POST',

			url: '<?php echo Yii::app()->createUrl("forumPost/forumUploadStatus"); ?>',

			data:data,

			success:function(data) {

				// $("#list-of-post").append(data);

				jQuery("#list-of-post").load("<?php echo Yii::app()->createUrl("forumPost/forumPostDisplay"); ?>");

				$("#ForumPost_content").val('');

			},

			error: function(data) { // if error occured

				alert("Error occured.please try again");

				 alert(data);

			},

			dataType:'html'

		});


}


$(document).ready(function() {

	$("#post-submit-btn").attr("disabled", "disabled");

});

function enableBtn(val) {

	if(val==null||val=="") {

		$("#post-submit-btn").attr("disabled", "disabled");

	} else {

		$("#post-submit-btn").removeAttr("disabled");

	}

}


</script>



_forumPost.php


<?php

        $this->widget('zii.widgets.CListView', array(

                'dataProvider'=>$dataProvider,

                'itemView'=>'_view',

        ));

?>

index.php


<div id="forumForm">

        <div id="simple-div">

                <?php echo $this->renderPartial('_uploadStatus', array('model'=>$model)); ?>

        </div>

</div>


<hr style="height: 1px;"/>


<div id="list-of-post" class="list-post">

	<?php

		echo $this->renderPartial('_ForumPost', array('dataProvider'=>$dataProvider));

	?>

</div>

Cheers! :)

and i want know one more thing is how to load the data in the view using jQuery append functionality for the same?

Hi, Selvam,

Change the ajax code as follows

in _uploadStatus.php file







success:function(data) {

                                // $("#list-of-post").append(data);

                                jQuery("#list-of-post").append(jQuery.load("<?php echo Yii::app()->createUrl("forumPost/forumPostDisplay"); ?>"));

                                $("#ForumPost_content").val('');

                        },




Probably you will be getting your exact output…

sorry, i didn’t get the output. now the only URL passes and stored in the database, but on success the data didn’t displayed in the view page.

Try this that code was not checked with jquery regular express \" so it will work now







success:function(data) {

                                // $("#list-of-post").append(data);

                                jQuery("#list-of-post").append(jQuery.load("<?php echo Yii::app()->createUrl(\"forumPost/forumPostDisplay\"); ?>"));

                                $("#ForumPost_content").val('');

                        },




When I’'m trying this one I’m getting the following error:


( ! ) Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting T_STRING in C:\wamp\www\nh\protected\views\forumPost\_uploadStatus.php on line 41