title: Codeigniter AJAX Example
body: <p>I've been looking for a week now for a decent full working example of how to use AJAX with Codeigniter (I'm an AJAX novice). The posts / tuts I've seen are old - all the programming languages have moved on.</p>
  
  <p>I want to have an input form on a page which returns something to the page (e.g. a variable, database query result or html formatted string) without needing to refresh the page. In this simple example is a page with an input field, which inserts the user input into a database. I'd like to load a different view once the input is submitted. If I could understand how to do this I'd be able to adapt it to do whatever I needed (and hopefully it would help others too!)</p>
  
  <p>I have this in my 'test' controller:</p>
  
  <pre><code>function add(){
      $name = $this-&gt;input-&gt;post('name');
      if( $name ) {
          $this-&gt;test_model-&gt;put( $name );
      }
  }
  
  function ajax() {
      $this-&gt;view_data["page_title"] = "Ajax Test";
      $this-&gt;view_data["page_heading"] = "Ajax Test";
  
      $data['names'] = $this-&gt;test_model-&gt;get(); //gets a list of names
      if ( $this-&gt;input-&gt;is_ajax_request() ) { 
          $this-&gt;load-&gt;view('test/names_list', $data);
      } else {
          $this-&gt;load-&gt;view('test/default', $data);
      }
  }
  </code></pre>
  
  <p>Here is my view, named 'ajax' (so I access this through the URL www.mysite.com/test/ajax)</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      jQuery( document ).ready( function() {
         jQuery('#submit').click( function( e ) {
             e.preventDefault();
             var msg = jQuery('#name').val();
             jQuery.post("
                 &lt;?php echo base_url(); ?&gt;
                 test/add", {name: msg}, function( r ) {
                     console.log(r);
                 });
             });
         });
  &lt;/script&gt;
  
  &lt;?php echo form_open("test/add"); ?&gt;
  &lt;input type="text" name="name" id="name"&gt;
  &lt;input type="submit" value="submit" name="submit" id="submit"&gt;
  &lt;?php echo form_close(); ?&gt;
  </code></pre>
  
  <p>All that happens currently is that I type in an input, updates the database and displays the view "test/default" (it doesn't refresh the page, but doesn't display "test/names_list" as desired. Many thanks in advance for any help, and for putting me out of my misery!</p>