upload image using codeigniter with ajax and formdata

前端 未结 3 1393
栀梦
栀梦 2020-12-20 07:40

I like to upload image using codeigniter Framework in PHP with JQuery AJAX without redirecting the page. When i upload the image it redirecting to controller area and the v

相关标签:
3条回答
  • 2020-12-20 08:19

    Try This. It's working-
    HTML Form-

    <form enctype="multipart/form-data" id="submit">
                   <div class="form-group">
                   <label for="menu">Select Menu</label>
                       <select class="form-control" name="selectmenuid" id="selectmenuid">
                        <option value="">-- Select Menu --</option>
                        <?php foreach($showData as $show):?>
                          <option value="<?php echo $show->menu_id?>"><?php echo $show->menu_name?></option>
                        <?php endforeach;?>
                        </select>
                    </div>
                   <div class="form-group">
                   <label for="menu">Select Sub Menu</label>
                       <select class="form-control" name="selectsubmenu" id="selectsubmenu">
                           <option>--Select Sub Menu--</option>
                        </select>
                   </div>
                  <div class="form-group">
                      <label for="imagetitle">Image Title</label>
                      <input type="text" class="form-control" name="imagetitle" id="imagetitle" placeholder="Enter Image Title" required="required">
                    </div>
                   <div class="control-group form-group">
                            <div class="controls">
                                <label>Upload Photo:</label>
                                <input name="file" type="file"  id="image_file" required>
                                <p class="help-block"></p>
                            </div>
                   </div>
                   <button type="submit" class="btn btn-primary" id="sub">Submit</button>
               </form>  
    

    Ajax -

    $('#submit').submit(function(e){
        e.preventDefault(); 
             $.ajax({
                 url:'Your path',
                 type:"post",
                 data:new FormData(this),
                 processData:false,
                 contentType:false,
                 cache:false,
                 async:false,
                  success: function(data){
                      alert(data);
               }
             });
        });  
    

    Just set url in ajax, It would work perfectly.
    Controller function-

    public function do_upload(){
            $config['upload_path']="./upload";
            $config['allowed_types']='gif|jpg|png';
            $this->load->library('upload',$config);
            if($this->upload->do_upload("file")){
            $data = array('upload_data' => $this->upload->data());
            $data1 = array(
            'menu_id' => $this->input->post('selectmenuid'),
            'submenu_id' => $this->input->post('selectsubmenu'),
            'imagetitle' => $this->input->post('imagetitle'),
            'imgpath' => $data['upload_data']['file_name']
            );  
            $result= $this->Admin_model->save_imagepath($data1);
            if ($result == TRUE) {
                echo "true";
            }
            }
    
         }
    
    0 讨论(0)
  • 2020-12-20 08:34

    this is simple.
    problem is the ajax
    you should stop the form submit first

    $('form').on('submit',function(e){//bind event on form submit.
       e.preventDefault();//stop submit
       .........          //your other codes
    
    0 讨论(0)
  • 2020-12-20 08:36

    This what i did to solve that problem

    HTML

          <div class="form-group">
                    <label for="logo">Service Provider Logo / Icon</label>
                    <input type="file" class="form-control" name="file" id="file" required="required">
                    <img src="#" id="img-logo"  alt="image" class="img-responsive" style="height: 200px !important;">
                    <input type="hidden" class="" id="returned-sp-id">
                </div>
                <div class="form-group">
                    <label for="caption">Service Provider Name</label>
                    <input type="text" class="form-control" id="caption" required="required">
                </div>
                <div class="form-group">
                    <label for="details">Service Provider Details</label>
                    <textarea type="text" class="form-control" id="details" required="required"></textarea>
                </div>
        </form>
    

    Jquery Ajax

          $(function() {
              $('#service-provider-details').on('submit', function(e){
                  var caption = $('#caption').val();
                  var details = $('#details').val();
    
                  var data = new FormData(this);
                  data.append('caption', caption);
                  data.append('details', details);
    
                  $.ajax({
                     url:'<?= base_url(), 'create_profile_sp/upload' ?>',
                     type:"post",
                     data: data,
                     processData:false,
                     contentType:false,
                     cache:false,
                     async:true,
                     success: function(data){
                       console.log(data);
                     }
                   });
                   e.preventDefault();
              });
          });
    

    The controller

          class Create_profile_sp extends CI_Controller
          {
    
            function __construct()
            {
               parent::__construct();
               $this->load->model('profile_sp_m');
            }
    
            public function upload($data) {
               $data = $_POST;
               $this->profile_sp_m->upload_logo($data);
            }
         }
    

    The model

         class profile_sp_m extends CI_Model
         {
            public $_tablename = 'profiles';
    
            function __construct()
            {
              // Call the Model constructor
              parent::__construct();
            }
    
            public function upload_logo($data) {
    
                $caption = $data['caption'];
                $details = $data['details'];
    
                if(isset($_FILES["file"]["type"]))
                {
                  $validextensions = array("jpeg", "jpg", "png");
                  $temporary = explode(".", $_FILES["file"]["name"]);
                  $file_extension = end($temporary);
    
                  if ((($_FILES["file"]["type"] == "image/png") ||($_FILES["file"]["type"] == "image/jpg") || 
                     ($_FILES["file"]["type"] == "image/jpeg") ) && 
                     ($_FILES["file"]["size"] < 100000) && 
                      in_array($file_extension, $validextensions)){
                     if ($_FILES["file"]["error"] > 0)
                      {
                          echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
                      } else {
                        $sourcePath = $_FILES['file']['tmp_name']; Store source path in a variable
                        $targetPath = "uploads/profiles/" . $_FILES['file']['name']; // The Target path where file is to be stored
                        move_uploaded_file($sourcePath,$targetPath); // Moving Uploaded file
                         // The Image Data
                         $imageData = [
                             'caption'   => $caption,
                             'description'   => $details,
                         ];
    
                         // Insert the data
                         $this->db->insert($this->_tablename, $imageData);
                      }
                  }
               }
    
            }
    
    
    
         }
    
    0 讨论(0)
提交回复
热议问题