Welcome Guest, Not a member yet? Register   Sign In
ci + jquery
#5

[eluser]onejaguar[/eluser]
Personally I do everything back and forth with JSON which ends up being a lot more flexible.

Here is the CodeIgniter Controller:

Code:
class Ajax extends Controller {

  var $json_data=Array(
    'error' => 1,
    'html' => 'Ajax Error: Invalid Request'
    );

  function __construct() {
    parent::Controller();
    $this->output->set_header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
    $this->output->set_header('Expires: '.gmdate('D, d M Y H:i:s', time()).' GMT');
    $this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
    $this->output->set_header("Pragma: no-cache");
  }

  function do_something() {
    $this->json_data['html'] = $this->load->view('someview', $_POST, true);
    $this->json_data['error'] = 0;
    $this->json_data['another_variable'] = 42;
  }

  function _output($output) {
    echo json_encode($this->json_data);
  }
}


Then in the script...

Code:
$.ajax({
    url: '/ajax/do_something/',
    type: 'POST',
    data: {field: value},
    dataType: 'json',
    timeout: 8000,
    success: success_function
  });

  function success_function(json) {
    if (json.error)
      alert(json.html);
    else
      $('#result_div').html(json.html);

    if (json.another_variable == 42)
      alert("I've found the secret of life!");
  }

Obviously much more useful data can be passed back and forth. Everything in the 'data' object on the Javascript side will be in $_POST in CodeIgniter. I have used this setup for two sites now; one with a single AJAX controller that acts as router redirecting to mini-modules; another which uses several controllers just for ajax calls. If you are doing the latter you could setup a parent AJAX controller object which gets extended by all your AJAX controllers.


Messages In This Thread
ci + jquery - by El Forum - 05-18-2008, 10:12 PM
ci + jquery - by El Forum - 05-19-2008, 02:55 AM
ci + jquery - by El Forum - 05-19-2008, 03:10 AM
ci + jquery - by El Forum - 05-19-2008, 03:35 AM
ci + jquery - by El Forum - 05-19-2008, 05:19 PM
ci + jquery - by El Forum - 05-20-2008, 09:45 AM
ci + jquery - by El Forum - 05-20-2008, 12:38 PM
ci + jquery - by El Forum - 05-24-2008, 06:00 PM
ci + jquery - by El Forum - 05-24-2008, 11:47 PM
ci + jquery - by El Forum - 05-25-2008, 08:34 PM
ci + jquery - by El Forum - 05-29-2008, 03:06 PM
ci + jquery - by El Forum - 05-29-2008, 04:04 PM
ci + jquery - by El Forum - 05-30-2008, 09:46 AM
ci + jquery - by El Forum - 08-18-2009, 12:27 AM
ci + jquery - by El Forum - 12-17-2009, 01:19 PM
ci + jquery - by El Forum - 12-18-2009, 04:44 AM
ci + jquery - by El Forum - 06-14-2010, 09:46 PM
ci + jquery - by El Forum - 09-12-2010, 08:14 PM



Theme © iAndrew 2016 - Forum software by © MyBB