user3367639
user3367639

Reputation: 597

Code Igniter File Uploading Class with Jquery Ajax

So all I am trying to accomplish is simply upload a file with codeigniter using the File Uploading Class

For my controller I have the following code:

function do_upload()
{
    $config['upload_path'] = './assets/productImages/';
    $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())
    {
        $error = array('error' => $this->upload->display_errors());

        var_dump($error);
    }
    else
    {
        $data = array('upload_data' => $this->upload->data());
    }
}

And then my form is as follows:

$data['productImage'] = array(
   "name" => "userfile",
   "id" => "product_image",
);

 // displays out as: 
 <input type="file" name="userfile" value="" id="product_image">

My javascript is as follows which uses an onchange action to trigger the upload process.

$("document").ready(function(){
            $("#product_image").change(function() {
                var path = $(this).val();
                var dataString = 'userfile=' + path;
                //alert(dataString); return false;
                $.ajax({
                    type: "POST",
                    url: "/account/do_upload/",
                    data: dataString,
                    success: function(data) {
                        alert(data);
                    }
                });
                return false;
            });
        });

When I run this code, I receive this message in the javascript alert

You did not select a file to upload.

What do I need to add to make this work? I'm guessing it has something to do with processing the upload through the javascript ajax.

*UPDATE DUE TO COMMENTS *

My form tag is as follows:

$data['newPostForm'] = array('id' => 'newPostForm', 'type' => 'multipart');

// And echoes out as :
 <form action="http://myurl.com/index.php/account/submitPost" method="post" accept-charset="utf-8" id="newPostForm" type="multipart">

Upvotes: 0

Views: 851

Answers (1)

EdL
EdL

Reputation: 435

Your codeigniter code looks fine.
The problem is that you can't upload files directly through Ajax. You need to do it though an iframe.
This plugin here works a treat.
Or if you only need it to work in html 5 then this should do the treat http://www.devbridge.com/projects/html5-ajax-file-upload/

Upvotes: -1

Related Questions