calling php function from javascript or AJAX

Hi folks,

I have a problem, I need to call a php function from javascript function periodically. It needs to be called once a users logs in, and maybe every 5 to 10 seconds after that. Can anyone give me, or point me to a very simple example of this being done?

Help is greatly appreciated

I would say you need to use Ajax. Something like CHtml::ajax();

You can see some examples of Ajax being used here:

I assume you would not need to do anything with the returned content, so your controller action could just return "TRUE" or something.

Thanks NaX, well what I need is when a user logs in is to check the db for something. If this is true it should show some buttons, if false, they shouldn’t be visible. At the moment I just have some logic in the view, which should be avoided I know, which checks a condition, if it’s true it displays some buttons, if not they are not displayed. Its not a function though, if I put that code in a function I guess I could call it with ajax. Does that make any sense?

It sounds like the check should be part of the user, why not make it part of the user object.

How to add more information to Yii::app()->user

Add information to Yii::app()->user by extending CWebUser

Something like:


class WebUser extends CWebUser {

	public function getSpecialCheck() {

		if (!$this->getIsGuest() && 'something' == 'something') {

			return TRUE;


		else {

			return FALSE;





Then in your view something like

<?php if (Yii::app()->user->specialCheck): ?>

	hello world

<?php else: ?>

	good by world

<?php endif; ?>

If you still need to do this check using ajax you can setup a controller action that calls this function then call that action using Ajax.

I hope that helps.

FYI, I would avoid making Ajax calls every 5-10 seconds that will slow down your site a lot. If you can get away with doing it without Ajax/JavaScript that would be the best solution for me.