Working with JSON

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

Getting ready

  1. Create a new application by using the yiic webapp tool.
  2. Create and set up a new database.
  3. Add a table named news with at least id, created_on, and title fields, as shown in the following code:
    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`))
  4. Generate a News model using Gii.

How to do it...

  1. Create a new controller named protected/controllers/NewsController.php as follows:
    <?php
    class NewsController extends Controller
    {
       public function filters()
       {
          return array(
             'ajaxOnly + data',
          );
       }
    
       public function actionIndex()
       {
          $this->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 = time();
          $news->save();
          echo "OK";
       }
    }
  2. Moreover, create a view named protected/views/news/index.php as follows:
    <div class="news-list">
       Loading…
    </div>
    
    <?php Yii::app()->clientScript->registerCoreScript("jquery")?>
    <script type="text/javascript">
       jQuery(function($) {
          var newsList = $('.news-list'),
    
          function updateNews(){
             newsList.html("Loading…");
             $.ajax({
                url: "<?php echo $this->createUrl('data')?>",
                dataType: 'json',
                cache: false,
                success: function(data) {
                  var out = "<ol>";
                  $(data).each(function(){
                    out+="<li>"+this.title+"</li>";
                  });
                  out += "</ol>";
                  newsList.html(out);
                }
             });
          }
    
          updateNews();
    
          setInterval(function(){
             updateNews()
          }, 2000);
       });
    </script>
  3. 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 to do it...

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 that it is included properly:

<?php Yii::app()->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 the 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.

See also

  • The Loading a block through AJAX recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.144.197