2

I need guidance for following Query.
I am Trying to upload a file or move a file to the desired directory, But It's get failed. On the form, all the other fields data passed to controller except input['file'] data.
Please go through the following code.

View :
Form is displayed using Bootstrap Modal only minimal code is posted

<form method="post" action="<?php //echo base_url().'admin/students/update_accomodation'; ?>" id="accform" enctype="multipart/form-data">
        <div class="form-group">
            <div class="row">
                    <div class="col-md-2">
                        <label>Students</label>
                    </div>
                    <div class="col-md-4">
                        <input type="text" name="student" value="" />
                    </div>  
                    <div class="col-md-2">
                        <label>Room</label>
                    </div>
                    <div class="col-md-4">
                        <input type="text" name="room" value="" />
                    </div>
            </div>      
        </div>
        <div class="form-group">
            <div class="row">
                    <div class="col-md-2">
                        <label>Stay</label>
                    </div>
                    <div class="col-md-4">
                        <select name="stay" class="form-control" id="stay">
                            <option value="1">1 Month</option>
                            <option value="2">2 Month</option>
                            <option value="3">3 Month</option>
                            <option value="4">4 Month</option>
                            <option value="5">5 Month</option>
                            <option value="6">6 Month</option>
                            <option value="7">7 Month</option>
                            <option value="8">8 Month</option>
                            <option value="9">9 Month</option>
                            <option value="10">10 Month</option>
                            <option value="11">11 Month</option>
                            <option value="12">12 Month</option>
                            <option value="18">18 Month</option>
                            <option value="24">24 Month</option>
                            <option value="36">36 Month</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label>Upload PDF</label>
                    </div>
                    <div class="col-md-4">
                        <input type="file" name="file" id="file" class="btn btn-default btn-file" />
                    </div>
            </div>  
        </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary accomodation">Submit</button>
  </div>
    </form>

Ajax
Is on same page and in footer, jquery.js file is loading pefectly, and other than file field data is also passed to controller.

<script>
$(document).ready(function()  {
    $(".accomodation").click(function(event)  {
        event.preventDefault();
        //var formData = $('#accform').serialize();
       // var formData = new FormData($(this)[0]);
        //var formData = $('#accform').formSerialize();
        //console.log(formData);
        //alert(JSON.stringify(formData));
        $.ajax({
            type: "POST",
            url: "<?php echo site_url('admin/students/update_accomodation'); ?>",
            data: $('#accform').serialize(),
            //data: new FormData($("#accform")[0]),
            processData: false,
            success: function(res)  {
                //var json = JSON.parse(res);
                var parsed = res;
                console.log(parsed);
                if(parsed.status_code == 1) {
                    alert('data inserted successfully');
                    window.location.href = "<?php echo site_url('admin/bookings'); ?>";
                }else {
                    alert(parsed.status);
                }
            }

        });
    });       
});

Controller

function update_accomodation()  {
    //form input validation
    $this->form_validation->set_rules('student_id','Student ID','trim|required');
    $this->form_validation->set_rules('room_id','Room ID','trim|required');
    $this->form_validation->set_rules('stay','stay','required');
    if (empty($_FILES['file']['name'])) {                        //check file is selected
        $this->form_validation->set_rules('file','File','required');
    }
    if($this->form_validation->run() == FALSE)  {               //form validation false
        $data = array(
            'status' => validation_errors(),
            'status_code' => 2
        );
        echo json_encode($data);
    }   else    {          
        //echo json_encode(array('data' => $_FILES['file']['name']));
        //form validation true
        if (0 < $_FILES['file']['error']) {
            $data = array(
                'status' => 'File uploading error',
                'status_code' => 3
            );
            echo json_encode($data);
    }   else    {
            $sourcePath = $_FILES['file']['tmp_name'];          //filename="file" 
            $targetPath = "uploads/students/contracts/".rand(0,10000).$_FILES['file']['name'];      //targetpath with random number as prefix
            move_uploaded_file($sourcePath,$targetPath);                                //move file to target folder
            $data1 = array(                                             //take inputs
                'stay' => $this->input->post('firstname'),
                'id_upload' => $targetPath
            );
            $data = array(
                'status' => 'upload successfully',
                'status_code' => 1
            );
            echo json_encode($data);
    }
}
}

What Errors I am Getting :
1) input['file'] value is not get passed, only input['text'] and other value get passed.
2) Form validation error for input['file'](offcourse because file value not get passed).

What I have done so far :
1)I tried Multiple types to accept form data, I comment it in ajax.
2)I tried jquery.form.min.js plugin(link : http://malsup.com/jquery/form/). after using this plugin the input['file'] value can get acceptet(traced in console) but not passed to controller, getting error undefined variable: file.
3) ProcessData: false, contentType: false, is also used.
4) enctype="multipart/form-data" is also included.

Final Thing to mention The above code working perfectly on another controller and view in existing project, I copied same code but it won't work on current controller. Need Help, Thank you.

Updated AJAX code suggested by User : but it won't work for me, as null values get passed to controller

<script>
$(document).ready(function()  {
    $(".accomodation").click(function(e)  {
        e.preventDefault();
        var formData = new FormData(this);
        $.ajax({
            type: "POST",
            url: "<?php echo site_url('admin/students/update_accomodation'); ?>",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function(res)  {
                console.log(res);
            }

        });
    });       
});

Acceptance of answer with correction Following answer work for me, Thank you so much.

var form = $('#accform');
var formData = new FormData(form[0]);

Instead

var formData = new FormData(this);
pra5hant
  • 93
  • 1
  • 8
  • @ADyson : Hi, I already checked above solution, but it won't work for me, any other suggestion after looking into the code, because above code is working on another controller and view. Thank you. – pra5hant Oct 23 '17 at 09:39
  • why doesn't it work for you, exactly? It clearly works for a lot of other people judging by the number of upvotes and its "protected" status. Have you got some special extra circumstance which makes your question different? I fail to see how the controller and view has any impact, that's just changing the URL - how does that make any difference to the process, in your opinion? – ADyson Oct 23 '17 at 09:41
  • In your code above, you have forgotten to set the contentType option, which is the most obvious mistake, there may be others, but you should start there. – ADyson Oct 23 '17 at 09:42
  • @ADyson : I don't know why it is not working for me, That's why I paste all of my code, if you can see I have mentioned that I tried processData: false and other things, do you think is there any other files impact on code like jquery? – pra5hant Oct 23 '17 at 09:51

1 Answers1

0

.serialize() cannot accept to upload files using Jquery & Axaj.

To achieve this use

$(document).ready(function (e) {
    $('.accomodation').on('submit',(function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    }));
  }));
Siddhartha esunuri
  • 1,104
  • 1
  • 17
  • 29