1

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?

1
  • 1
    you should return the array using json_encode, ex: return json_encode($timeArray);, and then the ajax part you should decode and iterate the array, as you want Commented Aug 28, 2013 at 5:47

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

2
<?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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.