Tuesday, July 9, 2013

Yii: Working with JSON

JSON is a very simple, compact, and therefore a widely used format for AJAX applications data exchange. Yii has a few handy ways to work with it. Therefore, let's create a simple application that will show news list and update it every two seconds.

Getting ready

  1. Create a new application by using the yiic webapp tool.
  2. Create and setup a new database.
  3. Add a table named news with at least id, created_on, and title fields:
  4. CREATE TABLE `news` (
        `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
        `created_on` int(11) unsigned NOT NULL,
        `title` varchar(255) NOT NULL,
        PRIMARY KEY (`id`)
    )
    
  5. Generate a News model using Gii.

How to do it...

  1. Create a new controller named protected/controllers/NewsController.php as follows:
  2. render('index');
        }
    
        public function actionData() {
            $criteria = new CDbCriteria();
            $criteria->order = 'created_on DESC';
            $criteria->limit = 10;
            $news = News::model()->findAll($criteria);
            echo CJSON::encode($news);
        }
    
        public function actionAddRandomNews() {
            $news = new News();
            $news->title = "Item #" . rand(1, 10000);
            $news->created_on = date("Y-m-d H:i:s", time());
            $news->save();
            echo "OK";
        }
    
    }
    
  3. Moreover, create a view named protected/views/news/index.php as follows:
  4. Loading…
    clientScript->registerCoreScript("jquery") ?>
  5. Now, run the index action of the news controller and try to add a few records into the news database table by running the addRandomNews action. Do not refresh the index page. News added will appear on the index page once every two seconds, as shown in the following screenshot:

How it works...

The index action does nothing special. It simply renders a view that includes a div container and some JavaScript code. As we are using jQuery, we need to ensure it is included:
clientScript->registerCoreScript("jquery")?>
Then, we define a function named updateNews and run it every 2,000 milliseconds using the core JavaScript setInterval function. In updateNews, we make an AJAX request to the data action of the same controller, to process the JSON response and replace the current content of placeholder div with formatted data. In actionData, we get the latest news and convert them to JSON format by passing the result to CJSON::encode.

There's more

For further information, refer to the following URLs:
  • http://api.jquery.com/category/ajax/
  • http://www.yiiframework.com/doc/api/CJSON/
  • http://www.yiiframework.com/doc/api/CClientScript/#registerCoreScript-detail

14 comments:

  1. what is the application of clientScript->registerCoreScript("jquery") ?>

    ReplyDelete