How to upload image in codeigniter using ajax with server validation How to upload image in codeigniter using ajax with server validation codeigniter codeigniter

How to upload image in codeigniter using ajax with server validation


serialize() method not able to post file data.

For sending file using ajax use FormData instead of serializing

HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.

View

<form action="Your controller method name" method="post" id="form_img" enctype="multipart/form-data" accept-charset="utf-8">        <div>            username : <input type="text" name="name">            <span class="error name"></span>        </div>        <div>            password : <input type="text" name="password">            <span class="error password"></span>        </div>        <div>            file : <input type="file" name="image">            <span class="error image"></span>        </div>        <input type="submit" name="submit" value="submit">        </form>

Jquery call

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script><script type="text/javascript">    $(document).ready(function() {        $("#form_img").submit(function(e){            e.preventDefault();            var formData = new FormData($("#form_img")[0]);            $.ajax({                url : $("#form_img").attr('action'),                dataType : 'json',                type : 'POST',                data : formData,                contentType : false,                processData : false,                success: function(resp) {                    console.log(resp);                    $('.error').html('');                    if(resp.status == false) {                      $.each(resp.message,function(i,m){                          $('.'+i).text(m);                      });                     }                }            });        });    });</script>

controller

function test_image() {        $this->load->library('form_validation');        $this->form_validation->set_rules('name', 'name', 'required');        $this->form_validation->set_rules('password', 'password', 'required');        $this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');        if ($this->form_validation->run() == TRUE) {            if($_FILES['image']['error'] != 0) {                $result['status'] = false;                $result['message'] = array("image"=>"Select image to upload");            } else {                $config['upload_path']       = 'images';                $config['allowed_types']     = 'gif|jpg|jpeg|png';                $this->load->library('upload',$config);                $this->upload->initialize($config);                if ($this->upload->do_upload('image'))                {                    $data['upload_data'] = $this->upload->data('file_name');                    $image_name = $data['upload_data'];                }                else                {                    $image_name = '';                }                $data = array(                'name'         => $this->input->post('name'),                'password'    => $this->input->post('password'),                'image'         => $image_name,                'joined_date'   => date('Y-m-d H:i:s')                );                $result['status'] = true;                $this->Perfect_mdl->c_insert($data);                $result['message'] = "Data inserted successfully.";            }        }else {            $result['status'] = false;            // $result['message'] = validation_errors();            $result['message'] = $this->form_validation->error_array();        }        echo json_encode($result);    }

Try this flow for upload image using ajax


Files cannot be uploaded with serialize() function, as it does not serialize files. Please try this approach:

     var data = new FormData(this);     $.ajax({       url : me.attr('action'),       dataType : 'json',       contentType : false,       processData : false,       type : 'POST',       data : data,       success: function(resp) { ... etc.


try this codein view

 $('#formElement').submit(function () {         var formData = new           FormData(document.getElementById("formElement"));            formData.append('image-file', $('#image-file')[0].files[0]);            $.ajax({            url: "<?php echo base_url('home/add')?>",            data: formData,            contentType: false,             processData: false,            type: 'POST',            beforeSend: function() {                        $('.loder_img').show();                            },            success: function ( data ) {               $('.loder_img').hide();                   var val = JSON.parse(data);                 //you can apply alerts or anything to show validation on                  view and in val all mesg of validation yon can see here in console.               console.log(val);            },            error: function (request, status, error) {                $('.loder_img').hide();                   alert(request.responseText);            }            });  });

and in your controller

 public function addPackage()    {         $this->load->library("form_validation");        //left side form        $this->form_validation->set_error_delimiters('', '');        $this->form_validation->set_rules('txt_desc', 'Remarks', 'required|trim');        $this->form_validation->set_rules('txt_store', 'Store', 'required|trim');    //upto so on according to your values    if( $this->form_validation->run() == false){    $error = array(                            "check_1" => form_error('check_1'),                            "txt_desc" => form_error('txt_desc'),                            "txt_store" => form_error('txt_store'),                            "txt_couple_name" => form_error('txt_couple_name'),                            "txt_couple_case" => form_error('txt_couple_case'),                            "txt_phone" => form_error('txt_phone'),                            "txt_date" => form_error('txt_date'),                            "txt_location" => form_error('txt_location'),                            "txt_address" => form_error('txt_address'),                            "txt_email" => form_error('txt_email'),                            );                    $msg = array('status' => 'invalid', 'msg'                                   =>$error,'allerror'=>validation_errors());                        echo json_encode($msg);        }else{         //insert it into database all file and values    if($_FILES["image-file"]["size"] != 0){                         $path= './uploads/image';                        $img = "image/".$this->Upload_model->image_upload($path, "", '', '', '',"image-file");                    }    $data = array(                        "basket" => $this->filter($this->input->post("check_1",true))........    );    //your insert query      }    }

and in your model to upload image and it will return the uploaded image if it is not upload hen it will return false or you can print the display errors and dont forget to change the path of storing image

model code

public function image_upload($upload_path, $max_width, $max_height, $min_width, $min_height, $filename)    {            $config['upload_path'] = $upload_path;            $config['file_name'] = date('Ymd_his_').rand(10,99).rand(10,99).rand(10,99);            $config['allowed_types'] = "gif|jpg|png|jpeg|JPG|JPEG|PNG|bmp";            $config['overwrite'] = FALSE;            $config['max_size'] = '0';            $config['max_width']  = $max_width;            $config['max_height']  = $max_height;            $config['min_width']  = $min_width;            $config['min_height']  = $min_height;            $config['max_filename']  = '0';            $config['remove_spaces']  = FALSE;            $this->load->library('upload', $config);            if ( ! $this->upload->do_upload($filename))                {                    /*$data['upload_data']['file_name'] = '';                    $msg = $this->upload->display_errors('');                    $this->session->set_flashdata('msg',$msg);                      $url = $_SERVER['HTTP_REFERER'];                    redirect($url); */                 return false;                               //return $error = array('error' => $this->upload->display_errors());                               }            else                {                    $data = array('upload_data' => $this->upload->data());                    $config['source_image'] = $config['upload_path'].$data['upload_data']['file_name'];                    $config['quality'] = '100%';                    $this->load->library('image_lib', $config);                    return $data['upload_data']['file_name'];                }    unset($config);    $this->image_lib->clear();    }