Skip to content Skip to sidebar Skip to footer

Uploading Image In A Form Using Codeigniter/ajax

what should I do if i can't upload an image in a form it successfully created but the file is shows 0 not the upload file. please help me thanks in advance! script in view where I

Solution 1:

What I have found out on uploading through ajax in CodeIgniter is that when we submit the form the images doesn't get uploaded. Because of this I used an extra js file "jquery.form.min.js" and the ajax upload went well. To implement it the script would look like:

$('#uploadimg').ajaxForm({
       //uploadimg is my form id            
        dataType: 'json',
        success: processJson
});
function processJson(data) {
        if(data.msg=="success"){
             alert('Upload is successful.');
        }
        else{
             alert('Upload couldn't be completed.');
        }
}

The form would be

<formaction="<?=base_url();?>controller/uploadImage/"method="post"enctype="multipart/form-data"id="uploadimg">

On submition this will call the uploadImg function in the controller and here saving the image and insertion in the database is done.

publicfunctionuploadImage(){
    //$id = $this->session->userdata('uid');$config[ 'upload_path' ]   = UPLOAD_DIR.'/newsletter/0';
    $config[ 'allowed_types' ] = 'gif|jpg|png';
    $config[ 'max_size' ]      = '1500';
    $config[ 'max_width' ]     = '1000';
    $config[ 'max_height' ]    = '1500';
    $image_name                = "files";
    $this->load->library( 'upload', $config );
    if ( $this->upload->do_upload( $image_name ) ) {
            $upload_data = $this->upload->data();
            if(!empty($upload_data)){
                $arg = array(
                            'name' => $upload_data[ 'file_name' ]
                );
                $this->modelName->insert($arg );
                $data['msg']="success";
            }
            else{
                $data['errmsg']="Couldnot upload the file!";
            }
    }
    else{
        $data['errmsg'] =$this->upload->display_errors();
    }
    echo json_encode($data);
}

Now this will trigger the processJson function in the script. And the upload shows the result.

You can find the javascript file on jquery.form.js.

I hope it works out for you.

Post a Comment for "Uploading Image In A Form Using Codeigniter/ajax"