Mehur Mehur - 1 month ago 7
Ajax Question

Ajax upload not working codeigniter

I am using codeigniter 3.1 . I want to post upload data using ajax.

Ajax upload file not working.

No error in console.

HTML

<?php echo form_open_multipart(site_url("upload/post")) ?>
<input type="file" id="userfile" name="userfile" value="">
<button id="post">Submit</button>
<?php echo form_close() ?>




JAVASCRIPT

$('#post').on('click', function () {

var upload = $("#userfile").val();

$.ajax({
url: window.location.href+'/post',
type: "POST",
data: {'userfile':upload}
});



CONTROLLERS

public function post()
{
$this->load->library("upload");
$file = $this->common->nohtml($this->input->post("userfile"));

$this->upload->initialize(array(
"upload_path" => 'upload',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE,
));

$data = $this->upload->data();

$image_file = $data['file_name'];

$this->data_models->update($this->data->INFO, array(
"image" => $image_file
)
);

}

Answer

One of the issues is that file uploading uses a different mechanism than the other form <input> types. That is why $this->input->post("userfile") isn't getting the job done for you. Other answers have suggested using javascript's FormData and this one does too.

HTML

A very simple form for picking a file and submitting it. Note the change from a simple button to <input type="submit".... Doing so makes it a lot easier for the javascript to use the FormData object.

FormData documentation

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <script src="https://code.jquery.com/jquery-2.2.2.js"></script>
        <title>Upload Test</title>
    </head>
    <body>

        <?= form_open_multipart("upload/post", ['id' => 'uploader']); ?>
        <input type="file" name="userfile">
        <p>
            <input type="submit" value="Upload">
        </p>
        <?php echo form_close() ?>

        <div id="message"></div>

        <script>
            $('#uploader').submit(function (event) {
                event.preventDefault();
                $.ajax({
                    url: window.location.href + '/post',
                    type: "POST",
                    dataType: 'json',
                    data: new FormData(this),
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        console.log(data);
                        if (data.result === true) {
                            $("#message").html("<p>File Upload Succeeded</p>");
                        } else {
                            $("#message").html("<p>File Upload Failed!</p>");
                        }
                        $("#message").append(data.message);
                    }
                });
            });
        </script>
    </body>
</html>

JAVASCRIPT

Use FormData to capture the fields. Note that instead of handling the button click we handle the submit event.

$('#uploader').submit(function (event) {
    event.preventDefault();
    $.ajax({
        url: window.location.href + '/post',
        type: "POST",
        dataType: 'json',
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data) {
            //uncomment the next line to log the returned data in the javascript console
            // console.log(data);
            if (data.result === true) {
                $("#message").html("<p>File Upload Succeeded</p>");
            } else {
                $("#message").html("<p>File Upload Failed!</p>");
            }
            $("#message").append(data.message);
        }
    });
});

CONTROLLER

I've added some code that "reports" results to ajax and will display it on the upload page.

class Upload extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(['form', 'url']);
    }

    public function index()
    {
        $this->load->view('upload_v');
    }

    public function post()
    {
        $this->load->library("upload");
        $this->upload->initialize(array(
                "upload_path" => './uploads/',
                'allowed_types' => 'gif|jpg|png|doc|txt',
                "overwrite" => FALSE,
                "max_filename" => 300,
                "encrypt_name" => TRUE,
        ));

        $successful = $this->upload->do_upload('userfile');

        if($successful)
        {
            $data = $this->upload->data();
            $image_file = $data['file_name'];
            $msg = "<p>File: {$image_file}</p>";
            $this->data_models->update($this->data->INFO, array("image" => $image_file));
        } else {
            $msg = $this->upload->display_errors();
        }

        echo json_encode(['result' => $successful, 'message' => $msg]);
    }

}

This will upload your file. Your work probably isn't done because I suspect that your are not saving all the file info you need to the db. That, and I suspect you are going to be surprised by the name of the uploaded file.

I suggest you study up on how PHP handles file uploads and examine some of the similar codeigniter related questions on file uploads here on SO.

Comments