2

I've been trying to figure out how to upload a file through ajax for the past several hours and nothing.

Here's the code: HTML:

<form action="" method="post" id="uploadForm" enctype="multipart/form-data">

  <input type="file" name="image" id="image">
  <input type="submit">

</form>

JS:

<script>

jQuery(document).ready(function(){  
  jQuery('form#uploadForm').on('submit', function(e){
    e.preventDefault();

    var file = jQuery('#image')[0].files[0];
    var form_data = new FormData( jQuery("form#uploadForm")[0] );
    form_data.append( 'image', file );

    jQuery.ajax({
      url: 'index.php?a=do',
      type: 'POST',
      processData: false,
      contentType: false,
      cache: false,
      data: form_data,
      success: function(response) {
        console.log(response);
      },
    });

    return false;

  });
});

</script>

PHP:

<?php 
$a = isset($_GET['a']) ? $_GET['a'] : '';
if($a <> '') {
  echo "result - ";
  var_dump($_POST);
  die();
}
?>

As a result I get an empty array, however if I leave the file field empty, then I get:

result - array(1) {
  ["image"]=>
  string(9) "undefined"
}

I've tried serialize(), serializeObject(), serializeArray(), $.param and every damn time I get "undefined function" error in console.

I went through dozens of similar questions on stackoverflow and nothing helped. I tried doing $.post instead of $.ajax and the "data" field which contains form_data is empty.

I need this for a Wordpress plugin and I'm trying to avoid using 3rd party JS plugins for the upload part.

Stefan
  • 218
  • 1
  • 4
  • 13

2 Answers2

3

$_FILES is where you check for uploaded files not $_POST.
Also in your code you actually upload the file twice as it is in the form you instantiated the form data object with then you add it again with append. Do either

var form_data = new FormData( jQuery("form#uploadForm")[0] );

or

var form_data = new FormData();
form_data.append( 'image', file );
Musa
  • 96,336
  • 17
  • 118
  • 137
  • 3 minutes after posting the question I figured I could try to dump $_FILES and it worked. Still, thanks for your answer. I replaced my code with this one http://stackoverflow.com/questions/21060247/send-formdata-and-string-data-together-through-jquery-ajax, I hope it helps someone. – Stefan Jan 24 '15 at 01:07
0
<html>
<head>
<title>Ajax file upload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST",             // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false,       // The content type used when sending data to the server.
cache: false,             // To unable request pages to be cached
processData:false,        // To send DOMDocument or non processed data file it is set to false
success: function(data)   // A function to be called if request succeeds
{
alert(data);
}
});
}));

</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
</body>
</html>
Nikit Barochiya
  • 971
  • 11
  • 14