79581

Upload files with Ajax and Jquery

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.

Answer1:

$_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 );

Answer2:

<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>

Recommend

  • How to upload a file using Ajax on POST?
  • When calling canvas.toDataURL, why is the part from rasterizeHTML.drawHTML black?
  • Jersey: MessageBodyReader not found for media type=multipart/form-data
  • How can I upload image use ajax on the vue.js 2?
  • SimpleXML - echo / print_r return different values
  • file_get_Contents won't send query strings in url , thus receiving nothing with $_GET
  • PHP FTP directory listing error
  • Why am I getting an Array of an Array with Doctrine 2 & Symfony 2 Data Transformer?
  • Index.php as custom error page
  • Encode string to match encoded form field name in PHP POST array
  • PHP file_exists() anomaly
  • array_search() in Session Array
  • testing a POST using phpunit in laravel 4
  • How does this usort cmp function actually work?
  • Stop Bash Script if Hive Fails
  • How to add git credentials to the build so it would be able to be used within a shell code?
  • Detect when Facebook like button is clicked
  • Needing to do .toArray() to get output of mongodb .find() on key name not value
  • Make VS2015 use angular-cli ng at build time in a .NET project
  • FB SDK and cURL: Unknown SSL protocol error in connection to graph.facebook.com:443
  • PHP - How to update data to MySQL when click a radio button
  • Perl system calls when running as another user using sudo
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Display Images one by one with next and previous functionality
  • Do I've to free mysql result after storing it?
  • Delete MySQLi record without showing the id in the URL
  • Apache 2.4 - remove | delete | uninstall
  • How to pass list parameters for each object using Spring MVC?
  • Numpy divide by zero. Why?
  • php design question - will a Helper help here?
  • A cron job substitute?
  • json Serialization in asp
  • AngularJs get employee from factory
  • Proper way to use connect-multiparty with express.js?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Authorize attributes not working in MVC 4
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?