Peter Pik Peter Pik - 8 months ago 25
Javascript Question

Illegal invocation when Post request an image

I'm trying to do a post request with an image, but I keep getting following error when I add it as a parameter

Uncaught TypeError: Illegal invocation
. I've tried this and
, but nothing seems to work.

var description = $('#description').val();
var title = $('#title').val();

var fileInput = $("#image")[0];

var file = fileInput.files[0];
var image = new FormData();
image.append('image', file);

type: 'POST',
url: 'insert.php',
data: {
desc: description,
title: title,
longitude: currentMarker.lng(),
success: function (answer) {



You can't put FormData into one of the parameters being sent, it has to be the entire data value. So it should be:

var image = new FormData();
image.append('image', file);
image.append('desc', description);
image.append('title', title);
image.append('longitude', currentMarker.lng());
    type: 'POST',
    url: 'insert.php',
    data: image,
    processData: false,
    contentType: false,
    success: function(answer) {

When sending FormData, you need to tell jQuery not to try to convert the data argument from an object to a URL-encoded string with processData: false.