Loading files via AJAX with CodeIgniter/MVC

2019-08-06 04:27发布

问题:

I'm currently in the process of rewriting an entire site of mine so that it's compatible with CI. I'm fairly new with CI and the MVC pattern in general. I followed this tutorial and have made a pretty decent template for the view part of the MVC pattern. The thing is, a lot of my site uses jQuery/AJAX to make it more dynamic. For example, on all of my pages on my site, I have an input field that uses jQuery to load a PHP file upon keyup.

<script type="text/javascript">
    $("#search_bar").keyup(function(){
        var search = $("#search_bar").val();
        var url = "search_bar.php";
        var data = "q="+ search;

        $('#livesearch').load(url, data);
        $("#livesearch").slideDown("fast");
    });
</script>

<input type='text' maxlength='30' id='search_bar' autocomplete='off' placeholder='Browse Teams' />
<div id='livesearch' style='display:none;'></div>

All of the backend work that's required to load the results happens in the PHP file that loaded via jQuery (search_bar.php). So, should "search_bar" be its own View that's triggered by its own Controller and then Modeled by a model called "search_bar"? Again, I'm very new to the MVC pattern and am not quite sure how properly integrate AJAX with a object oriented framework like CI.

Thanks

回答1:

Directly calling the view in ajax request is not a good practice call the controller which loads the view or directly do the stuff in the controller's function

<script type='text/javascript'>
    $('#search_bar').keyup(function(){
        $.ajax({
                url: 'yourcontrollername/search_bar_yourfunction',
                type:'POST',
                data: {q: search,
                success: function(result){
                 $("#livesearch").html(result);
                 $("#livesearch").slideDown("fast");
                    } 
                }); 
    });
    </script>

Your controller code

 class yourcontrollername extends My_Controller {
public function search_bar_yourfunction() {
      //do your stuff and store in the $data[] array

$this->load->view("search_bar",$data); //search_bar.php
die();
        }
    }
    }


回答2:

You should go from your View to the Controller:

<script type='text/javascript' language='javascript'>
    $('#search_bar').keyup(function(){
        $.ajax({
                url: 'search_bar.php',
                type:'GET',
                data: {q: search,
                success: function(result){
                        //Insert code here
                    } // End of success function of ajax form
                }); // End of ajax call
    });
    </script>

Then in your controller, load a model if necessary:

public function weigeren() {
        $user = $this->CI->authex->getUserInfo();
        $data['title'] = "Test";
        $this->load->model('search_model');
        $query = $this->input->get('q');
        if (isset($user)) {

          echo $this->search_model->search($query);


        }
    }


回答3:

I find one way to load ajax (jquery) in CodeIgniter 3. Example,

structure of folder:

  1. controllers/Upload.php
  2. view/admin/ajax_view/ajax_images.php

controllers/upload:

public function process()
{
    $data['my_picture'] = array(
        'pic_id' => '1', 
        'pic_path' => 'http://example.com/images', 
        );

    $this->load->view('admin/ajax_view/ajax_images', $data);
}

view/admin/ajax_view/ajax_images:

<?php foreach($my_picture as $key => $row): ?>
<td><?php echo $my_picture['pic_path']; ?></td>
<?php endforeach; ?>

view/admin/form_upload:

<tbody>
  <tr class="trbody">
    <th scope="row">1</th>
    <!-- <td></td> --> <!--comments this because appends element jquery-->
  </tr>
 </tbody>

<script type="text/javascript">
 $(document).ready(function(){
  $('#my_button').click(function(e){
   e.preventDefault;
    $.ajax({
      url: 'upload/process',
      dataType: 'text',
      type: 'post',
      success: function(data){
      $('.trbody')
      .append(
        '<td>'+ data + '</td>'
        );
      },
      error: function(errorThrown){
        console.log(errorThrown);
      }
    });
  });
});
</script>

To this way, I separated view of ajax of whole pages and load ajax view when event trigger.