Ajax Pagination in Codeigniter

Leave a Comment
We already did normal Pagination With Codeigniter. If you don't know how pagination is work in codeigniter then please go through first that tutorials.

In previous tutorial we already created all needed file for our pagination so let's continue with those files. Below image was our file structure.

Ajax Pagination in Codeigniter


For ajax pagination let's update our controller file i.e. pagination.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Pagination extends CI_Controller {

 function __construct(){
  parent::__construct();
  $this->load->model('mdl_pagination');
  $this->load->library('table');
  $this->load->helper("url");
 }

 public function country($offset=null)
 {
  $this->load->library('pagination');

  $config['base_url'] = base_url().'pagination/country/';    // url of the page
  $config['total_rows'] = $this->mdl_pagination->countcountry(); //get total number of records 
  $config['per_page'] = 10;  // define how many records on page
  $config['full_tag_open'] = '<ul class="pagination" id="search_page_pagination">';
  $config['full_tag_close'] = '</ul>';
  $config['cur_tag_open'] = '<li class="active"><a href="javascript:void(0)">';
  $config['num_tag_open'] = '<li>';
  $config['num_tag_close'] = '</li>';
  $config['cur_tag_close'] = '</a></li>';
  $config['first_link'] = 'First';
  $config['first_tag_open'] = '<li>';
  $config['first_tag_close'] = '</li>';
  $config['last_link'] = 'Last';
  $config['last_tag_open'] = '<li>';
  $config['last_tag_close'] = '</li>';
  $config['next_link'] = FALSE;
  $config['next_tag_open'] = '<li>';
  $config['next_tag_close'] = '</li>';
  $config['prev_link'] = FALSE;
  $config['prev_tag_open'] = '<li>';
  $config['prev_tag_close'] = '</li>';
  $config['page_query_string'] = FALSE;

  $this->pagination->initialize($config);

  $data['country'] = $this->mdl_pagination->getcountries($config['per_page'],$offset);
  $this->load->view('pagination',$data);
 }

}

We just added few parameter in pagination config for some basic design. Now lets update our view file
<html>
<head>
 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
 <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
 <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
 <div id="container">
  <h1>Countries</h1>
  <div id="body">
  <?php
   $this->table->set_heading('id', 'code', 'name');
   echo $this->table->generate($country);
   echo $this->pagination->create_links();
  ?>
  </div>
 </div>
   <script type="text/javascript">
   $(function(){
    $('body').on('click','ul#search_page_pagination>li>a',function(e){
      e.preventDefault();  // prevent default behaviour for anchor tag
      var Pagination_url = $(this).attr('href'); // getting href of <a> tag
     $.ajax({
      url:Pagination_url,
      type:'POST',
      success:function(data){
       var $page_data = $(data);
       $('#container').html($page_data.find('div#body'));
       $('table').addClass('table');
      }
     });
    });
   });
  </script>
</body>
</html>

this is our view file we don't need to change in modal file for this. Now you are wondering what's going on view file i will explain but first let's check how our view file look like.

Ajax Pagination in Codeigniter


Let's back to our code i hope you know jquery because we are using jquery with ajax. All magic goes with this below code.
<script type="text/javascript">
   $(function(){
    $('body').on('click','ul#search_page_pagination>li>a',function(e){
      e.preventDefault();  // prevent default behaviour for anchor tag
      var Pagination_url = $(this).attr('href'); // getting href of <a> tag
     $.ajax({
      url:Pagination_url,
      type:'POST',
      success:function(data){
       var $page_data = $(data);
       $('#container').html($page_data.find('div#body'));
       $('table').addClass('table');
      }
     });
    });
   });
  </script>

After document load if user click on one of the pagination link then we have to first remove default behaviour of anchor tag to remove that we use
e.preventDefault();
after that using "this" we got url of that clicked anchor tag after that call that url using ajax method. on success function of ajax we getting return data in "data params". We store that "data params" in jquery "$page_data". After that we have to find "div#body" from "$page_data" because all our pagination data in that div. After finding data we have to replace old data with new data in "#container" div. We will get next page data on our same page without refreshing page. The last line
$('table').addClass('table');
is just for design part. I am using same controller function for fist time load and ajax call you can separate both function and also i am loading same view for both call you can also separate both file then you don't need to write so much jquery in ajax success function you have just do something like this
success:function(data){
       $('#container').html(data));
       $('table').addClass('table');
      }

I did this all thing because to give you optimize code for ajax pagination in codeigniter.

Please comment down below if you have any query and please follows us for more awesome tutorials and keep motivating us .

Multiple file upload in codeigniter

Leave a Comment
Hello guy's, Today we gonna look how to upload Multiple file image with codeigniter. After single image upload with codeigniter. We gonna look multiple image upload in codeigniter. First we gonna look multi upload with same controller function after we move that function into helper so we can use somewhere else also. So let's start with controller file

Multi_upload.php (controller)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Multi_upload extends CI_Controller {

 function __construct(){
  parent::__construct();
 }

 public function index()
 {
  $arrData['error'] = '';
  $arrData['content'] = 'multi_image_upload';
  $this->load->view('template',$arrData);
 }

 public function do_multi_upload(){
  if($this->input->post('submit_form')){
   if($_FILES["profile_pic"]["tmp_name"]) {
    $this->do_miltiupload_files('./uploads/', 'M', $_FILES['profile_pic']); // call the function with params
   }
  }
 }

 function do_miltiupload_files($path, $title, $files)
    {   
        $config = array(
            'upload_path'   => $path,
            'allowed_types' => 'jpg|gif|png',
            'overwrite'     => 1,                       
        );

        $this->load->library('upload', $config);

        $images = array();

        foreach ($files['name'] as $key => $image) {
            $_FILES['multi_images[]']['name']= $files['name'][$key];
            $_FILES['multi_images[]']['type']= $files['type'][$key];
            $_FILES['multi_images[]']['tmp_name']= $files['tmp_name'][$key];
            $_FILES['multi_images[]']['error']= $files['error'][$key];
            $_FILES['multi_images[]']['size']= $files['size'][$key];
            // here we change file name on run time
            $fileName = $title .'_'. $image;
            $images[] = $fileName;
            $config['file_name'] = $fileName; //new file name

            $this->upload->initialize($config); // load new config setting 

            if ($this->upload->do_upload('multi_images[]')) { // upload file here
             echo "<pre>";
                print_r($this->upload->data());
                // performs your operations
            } else {
                return false;
            }
        }
        return $images;
    }
}
After controller let's create view part
<html>
<head>
<title>Upload Form</title>
</head>
<body>

<?php echo form_open_multipart('multi_upload/do_multi_upload');?>
   <input type="file" name="profile_pic[]" size="20" multiple/>
   <br /><br />
   <input type="submit" value="upload" name="submit_form"/>
</form>

</body>
</html>
now you can hit url on your localhost and try to select multiple file and upload. You get your data and performs your database operations. After uploading image you get this screen
Multiple file upload in codeigniter

How to upload image in codeigniter

Leave a Comment
Hello guy's, Today we gonna look how to upload image with codeigniter. In this tutorial we will use CodeIgniter's File Uploading Class which help to upload file. Using this class we can also set various preferences, restricting the type and size of the files.

Creating the Upload Form i.e. image_upload.php (View)

<html>
<head>
<title>Upload Form</title>
</head>
<body>

<?php echo form_open_multipart('image_upload/do_upload');?>
<input type="file" name="profile_pic" size="20" />
<br /><br />
<input type="submit" value="upload" name="submit_form"/>
</form>
<?php if($error) { echo ($error['error']); }?>

</body>
</html>
You'll notice we are using a form helper to create the opening form tag. File uploads require a multipart form, so the helper creates the proper syntax for you. You'll also notice we have an $error variable. This is so we can show error messages in the event the user does something wrong.

image_upload.php (Controller)

Using a text editor, create a controller called image_upload.php. In it, place this code and save it to your applications/controllers/ folder:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Image_upload extends CI_Controller {

function __construct(){
 parent::__construct();
        $this->load->helper(array('form', 'url'));
}

public function index()
{
 $arrData['error'] = '';
 $arrData['content'] = 'image_upload';
 $this->load->view('template',$arrData);
}

public function do_upload(){
 if($this->input->post('submit_form')){
  $config['upload_path'] = './uploads/';
  $config['allowed_types'] = 'gif|jpg|png';
  $config['max_size'] = '100';
  $config['max_width']  = '1024';
  $config['max_height']  = '768';

  $this->load->library('upload', $config);

  if ( ! $this->upload->do_upload('profile_pic'))
  {
                    $error = array('error' => $this->upload->display_errors());
   $arrData['error'] = $error;
   $arrData['content'] = 'image_upload';
   $this->load->view('template',$arrData);
  }
  else
  {
          $arrData['upload_data'] = $this->upload->data();
   $arrData['content'] = 'upload_success';
   $this->load->view('template',$arrData);
  }
 }
}
}
Now create uploads upload folder in root of your CodeIgniter installation and set its file permissions to 777.Now the last thing creating upload_success view

Creating upload Success view i.e upload_success.php (view)

<html>
<head>
<title>Upload Form</title>
</head>
<body>

<h3>Your file was successfully uploaded!</h3>
<ul>
<?php echo "<pre>"; print_r($upload_data); ?>
</ul>
<p><?php echo anchor('image_upload', 'Upload Another File!'); ?></p>
</body>
</html>
To try your form, visit your http://localhost/Proejct_foldername/image_upload. If you did't remove your index.php from url then you have to try with index.php in your url. Learn Here how to remove index.php from codeigniter Try uploading an image file (either a jpg, gif, or png). If the path in your controller is correct it should work. After successfully upload image you will get below output on upload_success page.
How to upload image in codeigniter

Powered by Blogger.