4

I am trying to upload a file on change of file input but I can't get it to work because I am not so good with javascript.

I did search on google and found this: How can I upload files asynchronously?

I used it and tried to change it to how I want to use it. But I am getting the error

`Uncaught TypeError: Illegal invocation`

This is my function:

function uploadFile(formData){
    $.ajax({
        url: 'inc/ajax/uploadFile.php',  //Server script to process data
        type: 'POST',
        data: {'formData':formData},
        //Ajax events
        success: function(html){
            alert(html);
        }
    });
}

I call the function like this:

$("input:file").change(function(){
    var file = this.files[0];
    uploadFile(file);
})

And uploadFile.php

<?php
 $formData = $_GET['formData'];
 echo $formData;
?>

I am just testing and trying to return the file in php to see if I can get it to work. But I have no idea on how I have to call it in PHP or send it with AJAX. I know how to upload it with PHP once I can retrieve the $_FILES in PHP.

Community
  • 1
  • 1

2 Answers2

3

In addition to the other answer, add this to your ajax

contentType: false,
processData: false

like:

var formData = new FormData();
formData.append('formData', file);
$.ajax({
    url: 'inc/ajax/uploadFile.php',  //Server script to process data
    type: 'POST',
    data: formData,
    contentType: false,
    processData: false,
    //Ajax events
    success: function(html){
        alert(html);
    }
});

You should also think about people that may not have a newer browser, and just put a little error message, like:

if(window.FormData === undefined){
    alert('sorry buddy, your browser\'s too old!');
    return;
}
genestd
  • 384
  • 3
  • 16
Prisoner
  • 27,391
  • 11
  • 73
  • 102
  • Thank you this fixed the error. But how do I have to call it in PHP? $_POST['formData'] doesn't work. –  Aug 22 '13 at 16:33
  • 1
    @Xegano, depending on what you named your form elements. do a `var_dump($_POST);` and `var_dump($_FILES);` - that will show you what data is being sent to the server. – Prisoner Aug 22 '13 at 16:33
  • Thanks! I had to call "$_FILES['formData']" and it returned the array. –  Aug 22 '13 at 16:37
2

You need to sent the data as a FormData object

function uploadFile(file){
    var formData = new FormData();
    formData.append('formData', file);
    $.ajax({
        url: 'inc/ajax/uploadFile.php',  //Server script to process data
        type: 'POST',
        data: formData,
        //Ajax events
        success: function(html){
            alert(html);
        }
    });
}

http://blog.new-bamboo.co.uk/2012/01/10/ridiculously-simple-ajax-uploads-with-formdata

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Thanks a lot this makes sense. But I am still getting the same error.. And the error comes from the line "data: formData," –  Aug 22 '13 at 16:26