Labeeb
Labeeb

Reputation: 369

Ajax in Codeigniter using jQuery

I have controller called Time

<?php
class Time extends CI_Controller {
  // just returns time
  public function index() {
    echo time();
  }
}
?>

this controller outputs the current time and that is loaded by using following code in a view.

window.setInterval(function() {
  $.get('time/index',
    // when the Web server responds to the request
    function(time) {
      $('#mydiv').html(time+'<br/>');
    }
  )
}, 5000);

As it can be seen only html response can be used only but what if I want Time controller to return array, object or even a variable etc how can I do that?

Upvotes: 1

Views: 406

Answers (2)

Habibillah
Habibillah

Reputation: 28695

You can use json-encode function on server side.

<?php
class Time extends CI_Controller {
  public function index() {
    // encode the what ever value (array, string, object, etc) 
    // to json string format
    echo json_encode(time());
  }
}
?>

and parse json with JSON.parse on javascript. Also you can use $.parseJSON

window.setInterval(function() {
  $.get('time/index',
    // when the Web server responds to the request
    function(returnedValue) {
      // parse json string to json object
      // and do object or varible manipulation
      var object = JSON.parse(returnedValue);
    }
  )
}, 5000);

Upvotes: 2

rfpdl
rfpdl

Reputation: 964

<?php

class Time extends CI_Controller 
{
  // just returns time
  public function index()
  {
    echo json_encode(array('time'=>time());
  }
} 

?>

and in your view

window.setInterval(
function()
{

$.get('time/index',

      // when the Web server responds to the request
        function(data) 
        {
          $('#mydiv').html(data['time']+'<br/>');
        },"JSON"
       )
}
,5000);

Upvotes: 2

Related Questions