Member Avatar for iamthwee

Hi,

I can successfully use the upload form in codeigniter without jquery/ajax, trouble is I need it for a rich text editor. Any ideas how to go abou this.

Ta.

Recommended Answers

All 11 Replies

Member Avatar for iamthwee
var form = new FormData(document.getElementById('upload_file'));
//append files
             var file = document.getElementById('userfile').files[0];
              if (file) {   
                  form.append('userfile', file);
              }

            $.ajax({
                type: "POST",
                url: "<?php echo site_url('blog/actual_insert_blog_post'); ?>",
                data: file,


                contentType: false, //must, tell jQuery not to process the data
                processData: false, //must, tell jQuery not to set contentType
                success: function(msg) 
                {
                    alert(msg);

                    if (msg == "1") 
                    {
                        window.location = "<?php echo site_url('landing/blog'); ?>"
                    } else {  

                      alert('Please fill in all fields!');
                    }
                }

            });

The important part is to specify contentType and processData to be false. By default as well, it passes in all the $_POST name data.

We use AJAX forms all the time and I don't specify contentType or processData. I use jQuery's post fn.

Member Avatar for iamthwee

Can you give an example... with a file upload.

Please allow me to give a simple example.

First, we will use this script right here. We will make some minor modifications so that it can work inside CI. Download and unzipped the zip file.

We will create our simple ajaxupload controller. This is going to be very basic. In fact, I am taking the liberty of not creating a model. However, you are always welcome to create a model file later on.

Step One:
In your codeigniter directory, create files/users/uploads directories if they don't exist. Our uploaded images will be saved in the uploads directory.

Step Two:
Let us create the most basic controller file named ajaxupload.php, and here are the codes. I am in the assumption here that you already autoload the basic libraries and helpers e.g. url helper.

filename: application/controllers/ajaxupload.php

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

    class Ajaxupload extends CI_Controller {


        public function __construct(){

            parent::__construct();

        }

        public function index(){

            $this->load->view('upload_view.php');


    }

        public function process_ajax(){

            if(is_array($_FILES)) {
                if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
                    $sourcePath = $_FILES['userImage']['tmp_name'];
                    $targetPath = "files/users/uploads/".$_FILES['userImage']['name'];

                if(move_uploaded_file($sourcePath,$targetPath)) {

    echo '<img src="'.base_url().$targetPath .'" width="100px" height="100px" alt="'.$_POST['image_title'].'"/>';

            }
        }
    }



    }
 }  

Don't worry about sanitization of the inputs for now. You can do them later after you are certain that uploaded files made it to the uploads directory.

Step three:
Create a view file application/views/upload_view.php

<html>
<head>
<title>PHP AJAX Image Upload</title>
<link href="<?php echo base_url(); ?>assets/css/styles.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
    $("#uploadForm").on('submit',(function(e) {
        e.preventDefault();
        $.ajax({
            url: "<?php echo base_url(); ?>ajaxupload/process_ajax",
            type: "POST",
            data:  new FormData(this),
            mimeType:"multipart/form-data",
            contentType: false,
            cache: false,
            processData:false,
            success: function(data)
            {
            $("#targetLayer").html(data);
            },
            error: function() 
            {
            }           
       });
    }));
});
</script>
</head>
<body>
<div class="bgColor">
<form id="uploadForm" action="ajaxupload/process_ajax" method="post" enctype="multipart/form-data">
<div id="targetLayer">No Image</div>
<div id="uploadFormLayer">
<label>Title</label><br/>
<input type="text" name="image_title" class="inputFile"/>
<br/>
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</div>
</body>
</html>

for now, don't worry about the doctype on the html page. We can do them later. As long as we are aware of it, we can play the lazy game :).

Step Four:
Create these directories if they don't exist assets/css/ inside your codeigniter directory.

Go back to the unzipped file earlier and look for the file named styles.css. Copy this css file to assets/css/ directory

Direct your browser to yoursite/ajaxupload/ and test your script. The image should appearing on the left hand side of the form after pressing on the submit button.

Additional info.

this method

public function process_ajax()

must be addressed like this inside the jquery code as url

url: "<?php echo base_url(); ?>ajaxupload/process_ajax",

remember the MVC framework convention? controllerObject/controller_method/ ?

That will conclude my simple tutorial.

Where do you from here?
Sanitize those form inputs.
Integrate the CI's native upload library

Remember the native CI upload library implementation?

    $config['upload_path'] = './files/users/uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '100';
    $config['max_width']  = '1024';
    $config['max_height']  = '768';
    $config['remove_spaces'] = TRUE;

if you want to have a unique name, use encrypt_name as part of config...

Happy uploading..........

Veedeoo

I just wanted to add that in production server, we need to serialize the response from the controller's process_ajax() method. You can use this tutorial as a guideline.

Member Avatar for iamthwee

I believe there are known issues with this failing on earlier version of internet explorer unless using an iframe.

I think I might have to rethink this and use a page refresh instead of ajax.

Member Avatar for iamthwee

I've done a lot of research and I don't like how formdata doesn't work for internet explorer version <10... Of all the research I believe that the following is probably the best solution working in older versions of internet explorer.

I will start integrating it into my CMS tomorrow.

https://github.com/LPology/Simple-Ajax-Uploader

Member Avatar for iamthwee

OK I'm making a right dog's dinner out of this one. I'm struggling.

Here is what I'd like to achieve.

  • I'd like to upload my form using ajax
  • I don't want to use form data because it isn't supported in internet explorer less than 10
  • I want to be able to still use the codeigniter upload class in my controller to control allowed file types and whatever.

So this is still unresolved. :(

Dani if you could post an example, I still don't get what you mean by you're just using jquery's post function.

Member Avatar for iamthwee

After much frustration I finally found a solution that works and is easy to read and more importantly has a fallback for internet explorer using iframe.

https://github.com/davgothic/AjaxFileUpload

What I found is that I just couldn't utilise codeigniter's file upload functions so I ended up using native php file upload instead.

My custom controller being:

public function upload()
    {
        $whitelist = array('jpg', 'jpeg', 'png', 'gif');
        $name      = null;
        $error     = 'No file uploaded.';

        if (isset($_FILES)) {
            if (isset($_FILES['file'])) {
                $tmp_name = $_FILES['file']['tmp_name'];
                $name     = basename($_FILES['file']['name']);
                $error    = $_FILES['file']['error'];

                if ($error === UPLOAD_ERR_OK) {
                    $extension = pathinfo($name, PATHINFO_EXTENSION);

                    if (!in_array($extension, $whitelist)) {
                        $error = 'Invalid file type uploaded.';
                    } else {
                        move_uploaded_file($tmp_name, "./img/$name");
                    }
                }
            }
        }

        $file_path = base_url("img/$name");

        echo json_encode(array(
            'name'  => $file_path,
            'error' => $error,
        ));
        die();

    }

I'm leaving this thread open in case anyone has more to add.

I just stumbled across this thread and wanted to point out that DaniWeb uses AJAX file upload with CodeIgniter's built-in library and an IFRAME.

hello veedeoo, sorry late to the party but this issue make me heck now ?
will you elaborate you script above with some validations ?

regards Freddy Sidauruk

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.