Vishal Kumar
Vishal Kumar

Reputation: 262

How to upload image in codeigniter using ajax with server validation

I have a form which data is inserting into data base through ajax. Along with when input fields has error then showing error under neath to the every fields.

But when i select the image and trying to upload the name of image into database, then nothing goes on, neither image uploading to the upload path nor inserting the name of the image into database.

In Case of image upload error i can not even display image upload error.

Controller:- In my Controller as you can see that i have an array named result which has two keys status and message and default status is false.

In the else part a loop is running which has only form error not any type of image error may be this is reason for not showing any error for image.

No Problem if error is not showing But at least file name should be inserting.

function infoValidation() {

$result = array('status' => false, 'message' => array());

$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run('company_registration')) {
        $config['upload_path']       = 'assets/uploads/';
        $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'];
            //$result['message'] = $this->upload->display_errors();
            //$result['status'] = false;
        }
        else
        {
            $image_name = '';   
        }

        $data = array(

            'email'         => $this->input->post('email'),
            'first_name'    => $this->input->post('firstname'),
            'last_name'     => $this->input->post('lastname'),
            'pincode'       => $this->input->post('pincode'),
            'state'         => $this->input->post('state'),
            'landmark'      => $this->input->post('landmark'),
            'address'       => $this->input->post('address'),
            'state'         => $this->input->post('state'),
            'image'         => $image_name,
            'joined_date'   => date('Y-m-d H:i:s')
            );


        $result['status'] = true;

        $this->Perfect_mdl->c_insert($data);


}else {


    foreach ($_POST as $key => $value) {

        $result['message'][$key] = form_error($key);
    }
}

echo json_encode($result);

}

Ajax:

$("#form").submit(function(e){
    e.preventDefault();
    var me = $(this);

    $.ajax({
        url : me.attr('action'),
        dataType : 'json',
        type : 'POST',
        data : me.serialize(),
        success: function(resp) {
            console.log(resp);
            if (resp.status == true) {
                $('#myModal').modal('show');

                $(".form-group").removeClass('has-error').removeClass('has-success');
                $(".text-danger").remove();
            }else {
                $('#msg').html('<div class="alert alert-danger"><h5>Please Check Your Details</h5></div>');
                $.each(resp.message, function(key, value) {

                    var element = $("#"+key);
                        element.closest('.form-group')
                                .addClass(value.length > 0 ? 'has-error' : 'has-success')
                                .find('.text-danger').remove();

                        if(element.parent('.input-group').length) {
                            element.parent().after(value);
                        } else {
                            element.after(value);
                        }
                    // element.after(value);
                });
            }
        }
    });     
});

How can i Upload an image into database, If this is not the right way then please Suggest the right way for doing this

Upvotes: 3

Views: 5962

Answers (4)

Nidhi
Nidhi

Reputation: 1539

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

Upvotes: 9

Rajat Masih
Rajat Masih

Reputation: 583

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();

    }

Upvotes: 3

Dilip kumar
Dilip kumar

Reputation: 176

Jquery serialize() method not able to post file data.

Please used jquery plugin for post file data using ajax. which are given below.

dmuploader.js
dmuploader.min.js

for simple example click here

Upvotes: 1

Kosh
Kosh

Reputation: 18393

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.

Upvotes: 3

Related Questions