1

I am storing some data from modal input. Everything works fine but when I work with file type data in this case I am taking an image which is to be stored in server folder and its location is to be stored in database.

  1. I check if user wants to add data
  2. then push the data to corresponding method of controller via ajax
  3. there, I store the image in selected folder and retake location of the image, then push all data to model to store them in database. Code:

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">Blog Form</h3>
        </div>
        <div class="modal-body form">
            <form id="form" class="form-horizontal" method='post' action='' enctype="multipart/form-data>
                <input type="hidden" value="" name="id"/>
                <div class="form-body">
                    <div class="form-group">
                        <label class="control-label col-md-3">Author Name</label>
                        <div class="col-md-9">
                            <input name="author" placeholder="author" class="form-control" type="text">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Blog Title</label>
                        <div class="col-md-9">
                            <input name="title" placeholder="title" class="form-control" type="text">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Blog Category</label>
                        <div class="col-md-9">
                            <input name="tag" placeholder="tag" class="form-control" type="text">

                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Blog Details</label>
                        <div class="col-md-9">
                            <input name="details" placeholder="details" class="form-control" type="text">

                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Blog Picture</label>
                        <div class="col-md-9">
                            <input name="picture" id="picture" placeholder="Add a photo" type="file">

                        </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 -->

Save function in script:

function save()
{
    var url;
    if(save_method == 'add')
    {
        url = "<?php echo site_url('index.php/admin/blog_add')?>";
    }
    else
    {
        url = "<?php echo site_url('index.php/admin/blog_update')?>";
    }
    $.ajax({
        url : url,
        type: "POST",
        data: $('#form').serialize(),
        dataType: "JSON",
        success: function(data)
        {
            //if success close modal and reload ajax table
            $('#modal_form').modal('hide');
            location.reload();// for reload a page
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error adding / update data');
        }
    });
}

Blog_add method in Admin controller:

public function blog_add(){
$picture_name = $this->store_photo_return_photo_location();
$data = array(
    'author' => $this->input->post('author'),
    'title' => $this->input->post('title'),
    'details' => $this->input->post('details'),
    'tag' => $this->input->post('tag'),
    'picture' => $picture_name,
);
$insert = $this->admin_model->blog_add($data);
echo json_encode(array("status" => TRUE));}

store_photo_return_photo_location function:

public function store_photo_return_photo_location(){
    $filename = $_FILES['picture']['name'];
    // Location
    $location = 'assets/images/'.$filename;
    // file extension
    $file_extension = pathinfo($location, PATHINFO_EXTENSION);
    $file_extension = strtolower($file_extension);
    // Valid image extensions
    $image_ext = array("jpg","png","jpeg","gif");
    $response = 0;
    if(in_array($file_extension,$image_ext)){
        // Upload file
        if(move_uploaded_file($_FILES['picture']['tmp_name'],$location)){
            $response = $location;
        }
    }
    return $response;}

model:

public function blog_add($data)
{
    $this->db->insert($this->table, $data);
    return $this->db->insert_id();
}

Until I worked with data without image, it was working ok, but when I'm working with image, it is not.

I think that pushing image name through ajax is not working.

Thanks in advance

renatodamas
  • 16,555
  • 8
  • 30
  • 51
arafat
  • 25
  • 8
  • 2
    is it showing any error? if it is showing any error, then what is it? could you please share that too? – Tazwar Utshas Oct 17 '18 at 08:51
  • Waht is your expected versus actual behaviour? Do you have any log entries, errors, warnings, notices? – delboy1978uk Oct 17 '18 at 08:53
  • Possible duplicate of https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload – misorude Oct 17 '18 at 08:59
  • You can not perform a file upload by using `$('#form').serialize()`. The documentation for this method explicitly mentions this: _“Data from file select elements is not serialized”_ – misorude Oct 17 '18 at 09:00
  • Shouldn't you be using codeigniter's file upload function? – Rotimi Oct 17 '18 at 09:11

3 Answers3

0

you are calling this function for uploading an image but not passing a 'post' data to that function

$this->store_photo_return_photo_location();

call it like this

$image = $this->input->post['picture'];
$this->store_photo_return_photo_location($image);

and modify your function

public function store_photo_return_photo_location($image) {
  //..your code
}
khan Farman
  • 346
  • 3
  • 11
0

javascript's serialize() function won't be able to grab file from the html form. You should use FormData() instead

data: new FormData($('#form')),

Also in your store_photo_return_photo_location() function verify that a file actually exists before proceeding with the upload

if(!empty($_FILES['picture']['name'])){
   //proceed
}
Rotimi
  • 4,783
  • 4
  • 18
  • 27
  • i tried your suggestion but it is not working. it is not giving alert('Error adding / update data'); but again modal is hiding too. so ajax function work seems to be unsuccessful. – arafat Oct 17 '18 at 10:06
0

There's a different approach to uploading a file via ajax. Please check this: https://stackoverflow.com/a/2320097/10412708

An easier approach is to put the submit URL in your form's action and let the form submit and refresh the page. Anyway, your JS reloads the page on success, why did you even use ajax for? Try to have your submit URL pre-conditioned in PHP if possible.

ACD
  • 1,431
  • 1
  • 8
  • 24