Search code examples
javascriptphpjqueryajaxfile-upload

Sending file together with form data via ajax post


I'm trying to upload a file via ajax together with some fields in a form. However, it doesn't work. I get this error.

Undefined Index :- File

Here's my code.

HTML

<!-- File Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for="file">Upload Software / File</label>
  
  <div class="col-md-4">
    <input id="file" name="file" class="input-file" type="file">
  </div>
</div>

<div class="form-group">
  <label class="col-md-4 control-label" for="price">Price($)</label>
  
  <div class="col-md-4">
    <input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
  </div>
</div>

Ajax

$("#add_product").click(function(e) {
  e.preventDefault();
  product_name = $("product_name").val();
  //d = $("#add_new_product").serialize();
  
  $.ajax({
    type: 'POST',
    url: 'ajax.php',
    data: $("#add_new_product").serialize(),
    success: function(response) {
      //
      alert(response);

    }
  })
});

PHP

if (0 < $_FILES['file']['error']) {
  echo ":!";
} else {
  echo "ASa";
}

What am I missing here?


Solution

  • Can you try using FormData():

    $("form#files").submit(function(){
    
        var formData = new FormData($(this)[0]);
    
        $.ajax({
            url: window.location.pathname,
            type: 'POST',
            data: formData,
            async: false,
            success: function (data) {
                alert(data)
            },
            cache: false,
            contentType: false,
            processData: false
        });
    
        return false;
    });
    

    The above is a sample code, but you may use it to modify it.