2

I am trying to upload a file along with other parameters using ajax. However, the files are not getting uploaded.

Form Code

<form id="first_form" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="file" accept="image/*" onchange="loadFile(event)">
    <input type="text" data-validation="url" class="form-control" id="first_name" name="first_name" placeholder="First Name" />
    <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name" />  
    <input type="image" src="<?php echo base_url(); ?>assets/images/icon/_Save.png" class="Save-container img-circle" id="submit_first_form">
</form>

Script Code

<script type="text/javascript">
  $(document).ready(function() {
    $("#submit_first_form").click(function(event) {
    event.preventDefault();
    var file = $("input#file").val(); 
    var first_name = $("input#first_name").val();
    var last_name = $("input#last_name").val();

    jQuery.ajax({
        type: "POST",
        url: "<?php echo base_url(); ?>" + "student/add_data",
        dataType: 'json',
        data: {
            file: file, 
            first_name: first_name,
            last_name: last_name
        },
        success: function(res) {
        if (res)
            {
                console.log(res);
            }
        }
    }); }); });
</script>

Controller Code

public function add_data()
    {
        $data = array(
            'file' => $this->input->post('file'),
            'first_name' => $this->input->post('first_name'),
            'last_name'=>$this->input->post('last_name')
        );

        $status = "";
        $msg = "";
        $file_element_name = $data['file'];

        $config['upload_path'] = 'www.localhost.com/project/assets/supplier';
        $config['allowed_types'] = 'gif|jpg|png|doc|txt';
        $config['max_size'] = 1024 * 8;
        $config['encrypt_name'] = TRUE;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload($file_element_name))
            {
                $status = 'error';
                $msg = $this->upload->display_errors('', '');
            }
        else
            {
                $data = $this->upload->data();
                //$data['file_name']
                $status = "success";
                $msg = "File successfully uploaded";
            }
        echo json_encode(array('status' => $status, 'msg' => $msg));
    }

Error that i am getting in console is:

{status: "error", msg: "You did not select a file to upload."}

Can anyone please tell how to upload file

4
  • 1
    try watching stackoverflow.com/questions/34151367/… Commented Dec 27, 2017 at 16:08
  • 1
    Possible duplicate of You did not select a file to upload. PHP Code Igniter Commented Dec 27, 2017 at 16:11
  • @Vickel tried the solution but still error is coming Commented Dec 27, 2017 at 16:26
  • 1
    @Leo Tried this solution, the form gets reloaded but the file is not getting uploaded Commented Dec 27, 2017 at 16:35

3 Answers 3

4

Try Using This code for script:

<script type="text/javascript">
    $(document).ready(function() {
    $("#submit_first_form").click(function(event) {
    event.preventDefault();
    var form_data = new FormData($('#first_form')[0]);

    jQuery.ajax({
        type: "POST",
        url: "<?php echo base_url(); ?>" + "student/add_data",
        data: form_data,
        processData: false,
        contentType: false,
        success: function(res) {
        if (res)
            {
                console.log(res);
            }
        }
    }); }); });
</script>
Sign up to request clarification or add additional context in comments.

6 Comments

I am still getting the same message, can you please once check the controller code also
Replace $file_element_name = $data['file']; with $file_element_name = $_FILES['file']; hope this will solve the issue.
Try changing this in your if condition: (!$this->upload->do_upload($file_element_name)) to if (!$this->upload->do_upload('file))
can you please try this and let me know whats the output print_r($_FILES); at the top of your function.
array is empty, i think the data is not getting passed
|
0
<form id="first_form" method="post" enctype="multipart/form-data">

The enctype when file upload.

Comments

0

-> give id in form tag Submit and add a submit button before form close script to send request $("#save").click(function (event) { event.preventDefault();

// Create an FormData object
    var data1 = new FormData($('#fileUploadForm')[0]);
      console.log($('#fileUploadForm'));
$.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "<?php echo base_url(); ?>" + "student/add_data",
        data: data1,
        processData: false,
        contentType: false,
        cache: false,

        success: function (data) {
        data = JSON.parse(data);
        console.log(data);
        if(data.id==1)
        {
          localStorage.setItem("user_profile_pic", data.user_pic);

          alert("updated sucessfully")

        }



        }
    });

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.