9
<form id="uploadForm" enctype="multipart/form-data" action="http://localhost:1337/ad/upload" method="post" name="uploadForm" novalidate>
    <input type="file" name="userPhoto" id="userPhoto" />
    <input type="submit" value="submit" id="uploadImage" />
</form>

This is my html form which accepts an image as file inout, the user can select an image file and then click submit. This works but the url of the current page changes to localhost:1337/ad/upload. I want the page to stay at the same url.

$("form#uploadForm").submit(function(event) {
    event.preventDefault();
    var formData = new FormData($(this)[0]);
    var posting = $.post(url, formData);

})

I have tried this to send the form using jquery but i get an error : Uncaught Type error : Illegal Invocation

What data does the form submit when the type is multipart /formdata and how can we get this data on jQuery

guradio
  • 15,524
  • 4
  • 36
  • 57
nikhil.g777
  • 882
  • 3
  • 12
  • 24

3 Answers3

27

processData

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

Please check jQuery Ajax Documentation

Try ajax like this -

var form = new FormData($("#uploadForm")[0]);
$.ajax({
        url: your_url,
        method: "POST",
        dataType: 'json',
        data: form,
        processData: false,
        contentType: false,
        success: function(result){},
        error: function(er){}
});
Developer
  • 324
  • 3
  • 13
1

You can give to the formData all form for processing

var form = $('#uploadForm')[0]; 
// You need to use standart javascript object here
var formData = new FormData(form);

or specify exact data for formdata

var formData = new FormData();
formData.append('userPhoto', $('input[type=file]')[0].files[0]); 
Rahul Patel
  • 5,248
  • 2
  • 14
  • 26
0

For those looking for a more modern approach, you can use the JS Fetch (without additional lib - jquery).

    var formData = new FormData(this);

    fetch(url, { 
      method: 'POST',
      body: formData
    })
    .then(response => {
      if (response.ok) {
        //success
      } else {
        throw Error('Server error');
      }
    })
    .catch(error => {
       console.log('fail', error);
    });
GetoX
  • 4,225
  • 2
  • 33
  • 30
  • If you are calling an MVC ActionResult controller, good luck getting the statusDescription back from the server when sending back a HttpStatusCodeResult response. – Post Impatica Aug 26 '22 at 18:53