2

I am trying to upload form data using ajax but the issue is that I am not able to upload image/file.

Form Code

<form class="form-inline" id="form_add"  enctype="multipart/form-data"> 
  <input type="file" id="file-input" name="file-input"  accept="image/*" >

  <input type="text" class="form-control name" id="fname" placeholder="First Name" >                            
  <select class="location" id="location" >
    <option value="">Location</option>
    <?php foreach($location as $loc): ?>
      <option value="<?php echo $loc->city.', '.$loc->state;?>" ><?php echo $loc->city.', '.$loc->state;?></option>
    <?php endforeach; ?>
  </select>
  <button type="submit" class="save_btn"  id="submit" > <img src="save.png" class="Save">   </button>
</form>

Script Code

<script>
  $("#submit").click(function()
    {
      event.preventDefault();
      var filename = $('input[type=file]').val();
      var fname = $("#fname").val();
      var location = $("#location").val();
      if(filename != "" || fname != "" || location != "")
            {
              $.ajax({
                type: "POST",
                url: "Data/add_data",
                data: {
                        filename : filename,
                        fname:fname,
                        location:location
                      },
                cache: false,
                success: function(result){
                  console.log(result);
                }});
            }
    });
</script>

Backend Code

$ImageFile = $this->input->post('filename');
$config['upload_path'] = './assets/client_img/.';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);

if (!$this->upload->do_upload('ImageFile')) 
    {
     $error1 = array('error' => $this->upload->display_errors());
     print_r($error1);
    }
else
    {
      $data1 = $this->upload->data();
      echo $data1['file_name'];
    }

In the backend code I am getting the value of $ImageFile as C:\fakepath\pic.jpg but the file is not getting uploaded and the error says that

You did not select a file to upload

Can anyone please tell how i can upload the file

Sam
  • 1,381
  • 4
  • 30
  • 70
  • You need to use FormData and to set processData: false, https://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery – angel.bonev Feb 16 '18 at 08:13
  • @angel.bonevusing the method told in suggested link will have to make me change my entire code, is there any alternate way – Sam Feb 16 '18 at 08:18
  • Why do you need to change entire code just chage data in ajax to data : FormData and create FormData something like that var formData = new FormData(); formData.append( 'filename', $( 'input[type=file]' )[0].files[0] ); formData.append( 'fname', $( '#fname' )[0].val() ); formData.append( 'location', $( '#location' )[0].val() ); – angel.bonev Feb 16 '18 at 08:27

4 Answers4

2
$("#submit").click(function ()
{
    event.preventDefault();
    var filename = $('input[type=file]').val();
    var fname = $("#fname").val();
    var location = $("#location").val();


    if (filename != "" || fname != "" || location != "")
    {
        var formData = new FormData();
        formData.append('filename', $('input[type=file]')[0].files[0]);
        formData.append('fname', fname);
        formData.append('location', location);
        $.ajax({
            type: "POST",
            url: "Data/add_data",
            data: formData,
            contentType: false,
            processData: false,
            cache: false,
            success: function (result) {
                console.log(result);
            }});
    }
});
angel.bonev
  • 2,154
  • 3
  • 20
  • 30
1

Few things I noticed

var filename = $('input[type=file]').val() 

Does not have a ;

Can you try to add the following fields:

 $.ajax({
            type: "POST",
            url: "Data/add_data",
            data: {
                    filename : filename,
                    fname:fname,
                    location:location
                  },

            contentType: false,
            processData: false,
            cache: false,
            success: function(result){
              console.log(result);
            }});
        }

Because it propbably has something to do with the contentType. It could also be the $this->upload->do_upload function, could be that you're not saving the file correctly. But you did not provide the code for that.

user2879055
  • 176
  • 9
  • The first issue is error that i made while posting question, i have corrected that, the second solution you gave, i tried that but still getting the same result – Sam Feb 16 '18 at 08:16
1

Try below code and make few changes in ajax code. Add below parameters in your code.

processData: false, contentType: false,

And add var formData = new FormData($("#form_add")[0]); line before ajax starts.

Or Check below code and make changes according to you code.

$("#submit").click(function(){
    event.preventDefault();
    var filename = $('input[type=file]').val();
    var fname = $("#fname").val();
    var location = $("#location").val();
    var formData = new FormData($("#addad")[0]);
    if(filename != "" || fname != "" || location != ""){
        $.ajax({
            type: "POST",
            url: "Data/add_data",
            data:formData,
            cache: false,
            processData: false,
            contentType: false,
            success: function(result){
                  console.log(result);
            }
        });
    }
});
Pankaj Makwana
  • 3,030
  • 6
  • 31
  • 47
1

Hi you need to serialize the form

<script>
  $("#submit").click(function()
    {
      event.preventDefault();

              $.ajax({
                type: "POST",
                url: "Data/add_data",
                data: $('#form_add').serialize(),
                cache: false,
                success: function(result){
                  console.log(result);
                }});
            }
    });
</script>

& in php check like

$ImageFile = $this->input->post('filename');
$config['upload_path'] = './assets/client_img/.';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);

if (!$this->upload->do_upload('ImageFile')) 
    {
     $error1 = array('error' => $this->upload->display_errors());
     print_r($error1);
    }
else
    {
      $data1 = $this->upload->data();
      echo $data1['file_name'];
    }
Swapnil Kumbhar
  • 440
  • 4
  • 10