jquery ajax – post form having file uploads

To post a form using jQuery Ajax, we can directly call jQuery .ajax() methods passing form data. The form data can be constructed using FormData. Note that here jQuery serialize() won’t work due to the presence of file uploads. Also note that FormData does not work in IE.

Here is code snippet which uses jQuery Ajax to submit a form. Just select any file and click submit to see the Ajax response.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<form id="form1" action="/api/post-dump.php" method=POST>
name1: <input type="text" name="name1" value="value1" /><br/>
file1: <input type="file" name="file1" value="value2" />
<input type="submit" name="submit" value="submit"/>
Response from server:
<pre id="result" style="background-color:lightgray;"></pre>

<script type="text/javascript">
$("#form1").submit(function() {
  var action = $("#form1").attr("action");
  data = new FormData($("#form1")[0]);
    url: action,
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
  return false;

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments