views:

482

answers:

1

I'm writing my first Codeigniter web app, and I'd like to use AJAX to pull some info for a modal box. Can somebody guide me through an easy way to incorporate ajax w/ CI?

Specifically, the user will click on a link, and instead of being taken to another page, that page will be loaded into a modal box.

Thanks!

+2  A: 

Answering you question, and since CI doesn't seem to have implemented yet a proper support to javascript libraries, you can use a function like this to ensure that the information you're dealing with comes from ajax :

http://snipplr.com/view/1060/check-for-ajax-request/

Note that this only works with javascript libraries like jQuery or MoonTools

After that, you just need to deal with the information as if it was a normal page, getting the data with $this->input->post('field') or $this->input->get('field') sanitized variables.

in a example (using jquery), suppose you have a anchor tag that you want to delete a row in a list of items :

$(function() {

  $('a.delete').click(function(e) {
  // prevents the default behaviour of the anchor
  e.preventDefault();
  // gets the id stored in the anchor as attribute
  var cid= $(this).attr('cid');

  // instantiate and executes the ajax
  $.ajax({
    type: 'POST',
    url: 'http://www.yoursite.com/ajax.php',
    data: "action=delete&cid="+cid,
    async: true,
    success: function(data){
    // alerts the response, or whatever you need
    alert(data);
  }
  });
});

After that, you just need to build your code in CI as a normal page. Note that I used normal url's in the ajax request (url for the base, data for the parameters), and don't know if it works properly with "url_rewrited" urls, but they might work with no problems, if you just use "url:" ajax parameter to insert the full url.

yoda
I'd really appreciate an example! :)
Kevin Brown
except instead of http://example.com/somepage.php , in CI you'd normally put in http://example.com/index.php/someclass/somemethod or http://example.com/class/method
andyk
I've modified this to work with my modal. Thank you very much!
Kevin Brown