1

I am making an admin panel in codeigniter. I have a table games. It has an image inside it. I want to upload that image using ajax. But for some reason, the image is not being uploaded and error occurs no file selected.

Controller

public function ajax_add() {
    $this->_validate();

    $config = [
        'upload_path' => './assets/game_images/',
        'allowed_types' => 'gif|png|jpg|jpeg'
    ];
    $this->load->library('upload', $config);
    if ($this->upload->do_upload()) {
        $file = $this->upload->data();
        $file_name = $file['file_name'];

        if ($file_name == '') {
            $data['error_string'][] = 'Please upload an image.';
            $data['status'] = FALSE;
            echo json_encode($data);
            exit();
        }
    } else {
        $data['inputerror'][] = 'image';
        $data['error_string'][] = $this->upload->display_errors();
        $data['status'] = FALSE;
        echo json_encode($data);
        exit();
    }

    $data = array(
        'title' => $this->input->post('title'),
        'iframe' => $this->input->post('iframe'),
        'status' => $this->input->post('status'),
        'category_id' => $this->input->post('category_id'),
        'image' => $file_name
    );
    $insert = $this->game->save($data);
    echo json_encode(array("status" => TRUE));
}

public function ajax_update() {
    $this->_validate();
    $data = array(
        'title' => $this->input->post('title'),
        'iframe' => $this->input->post('iframe'),
        'status' => $this->input->post('status'),
        'category_id' => $this->input->post('category_id')
    );
    $this->game->update(array('id' => $this->input->post('id')), $data);
    echo json_encode(array("status" => TRUE));
}

HTML

<div class="container">
    <h1 style="font-size:20pt">Games</h1>
    <h3>Game Data</h3>
    <br />
    <button class="btn btn-success" onclick="add_game()"><i class="glyphicon glyphicon-plus"></i> Add Game</button>
    <button class="btn btn-default" onclick="reload_table()"><i class="glyphicon glyphicon-refresh"></i> Reload</button>
    <br />
    <br />
    <table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Title</th>
                <th>Category</th>
                <th>Status</th>
                <th style="width:125px;">Action</th>
            </tr>
        </thead>
        <tbody>
        </tbody>

        <tfoot>
            <tr>
                <th>Title</th>
                <th>Category</th>
                <th>Status</th>
                <th>Action</th>
            </tr>
        </tfoot>
    </table>
</div>

Javascript

<script type="text/javascript">

    var save_method; //for save method string
    var table;

    $(document).ready(function () {

        //datatables
        table = $('#table').DataTable({
            "processing": true, //Feature control the processing indicator.
            "serverSide": true, //Feature control DataTables' server-side processing mode.
            "order": [], //Initial no order.

            // Load data for the table's content from an Ajax source
            "ajax": {
                "url": "<?php echo site_url('game/ajax_list') ?>",
                "type": "POST"
            },
            //Set column definition initialisation properties.
            "columnDefs": [
                {
                    "targets": [-1, -3], //last column
                    "orderable": false, //set not orderable
                },
            ],
        });

        //set input/textarea/select event when change value, remove class error and remove text help block 
        $("input").change(function () {
            $(this).parent().parent().removeClass('has-error');
            $(this).next().empty();
        });
        $("textarea").change(function () {
            $(this).parent().parent().removeClass('has-error');
            $(this).next().empty();
        });
        $("select").change(function () {
            $(this).parent().parent().removeClass('has-error');
            $(this).next().empty();
        });

    });



    function add_game()
    {
        save_method = 'add';
        $('#form')[0].reset(); // reset form on modals
        $('.form-group').removeClass('has-error'); // clear error class
        $('.help-block').empty(); // clear error string
        $('#modal_form').modal('show'); // show bootstrap modal
        $('.modal-title').text('Add Game'); // Set Title to Bootstrap modal title
    }

    function edit_game(id)
    {
        save_method = 'update';
        $('#form')[0].reset(); // reset form on modals
        $('.form-group').removeClass('has-error'); // clear error class
        $('.help-block').empty(); // clear error string

        //Ajax Load data from ajax
        $.ajax({
            url: "<?php echo site_url('game/ajax_edit/') ?>/" + id,
            type: "GET",
            dataType: "JSON",
            success: function (data)
            {

                $('[name="id"]').val(data.id);
                $('[name="title"]').val(data.title);
                $('[name="iframe"]').val(data.iframe);
                $('[name="status"]').val(data.status);
                $('[name="category_id"]').val(data.category_id);
                $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
                $('.modal-title').text('Edit Game'); // Set title to Bootstrap modal title

            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert('Error get data from ajax');
            }
        });
    }

    function reload_table()
    {
        table.ajax.reload(null, false); //reload datatable ajax 
    }

    function save()
    {
        $('#btnSave').text('saving...'); //change button text
        $('#btnSave').attr('disabled', true); //set button disable 
        var url;

        if (save_method == 'add') {
            url = "<?php echo site_url('game/ajax_add') ?>";
        } else {
            url = "<?php echo site_url('game/ajax_update') ?>";
        }

        // ajax adding data to database
        $.ajax({
            url: url,
            type: "POST",
            data: $('#form').serialize(),
            dataType: "JSON",
            success: function (data)
            {

                if (data.status) //if success close modal and reload ajax table
                {
                    $('#modal_form').modal('hide');
                    reload_table();
                } else
                {
                    for (var i = 0; i < data.inputerror.length; i++)
                    {
                        $('[name="' + data.inputerror[i] + '"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
                        $('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[i]); //select span help-block class set text error string
                    }
                }
                $('#btnSave').text('save'); //change button text
                $('#btnSave').attr('disabled', false); //set button enable 


            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert('Error adding / update data');
                $('#btnSave').text('save'); //change button text
                $('#btnSave').attr('disabled', false); //set button enable 

            }
        });
    }

    function delete_game(id)
    {
        if (confirm('Are you sure delete this data?'))
        {
            // ajax delete data to database
            $.ajax({
                url: "<?php echo site_url('game/ajax_delete') ?>/" + id,
                type: "POST",
                dataType: "JSON",
                success: function (data)
                {
                    //if success reload ajax table
                    $('#modal_form').modal('hide');
                    reload_table();
                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    alert('Error deleting data');
                }
            });

        }
    }

</script>

<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h3 class="modal-title">Game Form</h3>
            </div>
            <div class="modal-body form">

                <?php
                $attributes = array(
                    'id' => 'form',
                    'class' => 'form-horizontal'
                );

                echo form_open_multipart('#', $attributes);
                ?>
                <input type="hidden" value="" name="id"/> 
                <div class="form-body">
                    <div class="form-group">
                        <label class="control-label col-md-3">Title</label>
                        <div class="col-md-9">
                            <input name="title" placeholder="Title" class="form-control" type="text">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Iframe</label>
                        <div class="col-md-9">
                            <textarea name="iframe" placeholder="Iframe" class="form-control" type="text"></textarea>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Category</label>
                        <div class="col-md-9">
                            <select name="category_id" class="form-control">
                                <option value="">--Select Category--</option>
                                <?php foreach ($categories as $category) { ?>
                                    <option value="<?php echo $category['id'] ?>"><?php echo $category['name'] ?></option>
                                <?php } ?>
                            </select>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Image</label>
                        <div class="col-md-9">
                            <?php echo form_upload(['name' => 'image']); ?>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Status</label>
                        <div class="col-md-9">
                            <select name="status" class="form-control">
                                <option value="">--Select Status--</option>
                                <option value="0">Inactive</option>
                                <option value="1">Active</option>
                            </select>
                            <span class="help-block"></span>
                        </div>
                    </div>
                </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->
2
  • you need to use ajax file upload library. Commented Oct 4, 2016 at 5:53
  • Only add relent AJAX codes and tell what is the AJAX you are calling Commented Oct 4, 2016 at 12:14

4 Answers 4

2
+50

Noticed several required condition you missed in code

First in your ajax_add method

if ($this->upload->do_upload()) this should contain image field name like

if ($this->upload->do_upload('image')){// as your file upload field name is "image"

}

Then for ajax upload your client side code some params are missing

 contentType: false,
 processData: false,

so your ajax method should (in save method) looks like

$.ajax({
        url: url,
        type: "POST",
        data: $('#form').serialize(),
        dataType: "JSON",
        contentType: false,
        processData: false
       .....

processData this is important when file upload via ajax

Sign up to request clarification or add additional context in comments.

2 Comments

When I add content type and process data, my form contains errors. When I remove them I still get error that you did not select file to upload.
Now test echo form_open_multipart('#', $attributes); to echo form_open_multipart('controller/ajax_add', $attributes);
1

In addition to the suggestions from Rejoanul, you may want to check that you are not uploading a file that is too large.

Apparently if the file you are attempting to upload is larger than the maxsize, the FILES variable will be empty.

https://stackoverflow.com/a/21633123/2153218

Comments

0

Try to change This line in your controller

$img = "img"; // input name="img"
$this->upload->do_upload($img);

Comments

0

Try this

$config = array( 'upload_path' => './assets/game_images/',
                  'allowed_types' => 'gif|png|jpg|jpeg'
                  'overwrite' => TRUE, );

get_instance()->load->library('upload', $this->config); 
if($this->upload->do_upload('image')) { 
    echo "file upload success"; 
} else { 
    echo $this->upload->display_errors(); 
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.