最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Codeigniter AJAX Example - Stack Overflow

programmeradmin4浏览0评论

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.

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!)

I have this in my 'test' controller:

function add(){
    $name = $this->input->post('name');
    if( $name ) {
        $this->test_model->put( $name );
    }
}

function ajax() {
    $this->view_data["page_title"] = "Ajax Test";
    $this->view_data["page_heading"] = "Ajax Test";

    $data['names'] = $this->test_model->get(); //gets a list of names
    if ( $this->input->is_ajax_request() ) { 
        $this->load->view('test/names_list', $data);
    } else {
        $this->load->view('test/default', $data);
    }
}

Here is my view, named 'ajax' (so I access this through the URL www.mysite/test/ajax)

<script type="text/javascript">
    jQuery( document ).ready( function() {
       jQuery('#submit').click( function( e ) {
           e.preventDefault();
           var msg = jQuery('#name').val();
           jQuery.post("
               <?php echo base_url(); ?>
               test/add", {name: msg}, function( r ) {
                   console.log(r);
               });
           });
       });
</script>

<?php echo form_open("test/add"); ?>
<input type="text" name="name" id="name">
<input type="submit" value="submit" name="submit" id="submit">
<?php echo form_close(); ?>

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!

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.

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!)

I have this in my 'test' controller:

function add(){
    $name = $this->input->post('name');
    if( $name ) {
        $this->test_model->put( $name );
    }
}

function ajax() {
    $this->view_data["page_title"] = "Ajax Test";
    $this->view_data["page_heading"] = "Ajax Test";

    $data['names'] = $this->test_model->get(); //gets a list of names
    if ( $this->input->is_ajax_request() ) { 
        $this->load->view('test/names_list', $data);
    } else {
        $this->load->view('test/default', $data);
    }
}

Here is my view, named 'ajax' (so I access this through the URL www.mysite./test/ajax)

<script type="text/javascript">
    jQuery( document ).ready( function() {
       jQuery('#submit').click( function( e ) {
           e.preventDefault();
           var msg = jQuery('#name').val();
           jQuery.post("
               <?php echo base_url(); ?>
               test/add", {name: msg}, function( r ) {
                   console.log(r);
               });
           });
       });
</script>

<?php echo form_open("test/add"); ?>
<input type="text" name="name" id="name">
<input type="submit" value="submit" name="submit" id="submit">
<?php echo form_close(); ?>

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!

Share Improve this question edited Jan 18, 2013 at 15:43 Tepken Vannkorn 9,72314 gold badges62 silver badges86 bronze badges asked Dec 14, 2012 at 22:22 whispersanwhispersan 1,0392 gold badges13 silver badges28 bronze badges 14
  • Really your controller only set array values. Where do you load your views? (I'm only using jQuery for ajax which would reduce your js code to 1/10 of now) – jtheman Commented Dec 14, 2012 at 22:28
  • On this occasion, i'l remend jquery. Or else, open up the js console in browser and look at the errors. – itachi Commented Dec 14, 2012 at 22:33
  • Views are loaded automatically in my controllers, as I have this function in a main controller to do it: // set the default content view if ( $this->content_view !== FALSE && empty($this->content_view) ){ $this->content_view = $this->router->class . '/' . $this->router->method; } // render the content view $yield = file_exists(APPPATH . 'views/' . $this->content_view . EXT) ? $this->load->view($this->content_view, $this->view_data, TRUE) : FALSE; – whispersan Commented Dec 14, 2012 at 22:35
  • Please could you suggest the appropriate jQuery code which would achieve what I'm trying to do in this example? The jQuery examples I have tried from other sites have been flawed but I'm not good enough to write it myself – whispersan Commented Dec 14, 2012 at 22:37
  • 1 Look at the jquery in the answer to this question: stackoverflow./questions/12352404/… – jtheman Commented Dec 14, 2012 at 22:39
 |  Show 9 more ments

1 Answer 1

Reset to default 9

Set unique id to the form:

echo form_open('test/add', array('id'=>'testajax'));

I assume that you want replace a form with a view:

jQuery(document).ready(function(){
var $=jQuery;
$('#testajax').submit(function(e){
    var $this=$(this);
    var msg = $this.find('#name').val();
    $.post($this.attr('action'), {name: msg}, function(data) {
      $this.replace($(data));
    });
    return false;
});

better way if you return url of view in json response:

$.post("<?php echo base_url(); ?>test/add", {name: msg}, function(data) {
  $this.load(data.url);
},"json");


from your last ment - I strongly not suggest to replace body, it will be very hard to support such code.

but here is anser:

$.post("<?php echo base_url(); ?>test/add", {name: msg}, function(data) {
      $('body').replace(data);
    });
发布评论

评论列表(0)

  1. 暂无评论