3

I'm testing out sending a formData object to PHP (I am following http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/), but am having some difficulty getting it off the ground. First, the formData object is created and populated with:

var formdata = new FormData();
formdata.append('my_key','my_value');

Then my ajax call with jQuery is:

  $.ajax({
     url: 'php_upload.php',
     type: 'POST',
     cache: false,
     data: formdata,
     processData: false,
     contentType: false,
     success: function (response) {
     console.log(response);
  }
  }); 

With the php_upload.php file containing:

<?php
    echo $_FILES['my_key']['name'];
?>

But I get an undefined index: my_key error in the console.

Anyone have any idea what I might be doing wrong? Been scratching my head for ages.

1 Answer 1

8

You haven't added any files to the FormData, just a string which can be accessed by $_POST['my_key'].

To pass a file the second parameter of FormData.append has to be a FILE or a BLOB.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh I see. Got it working now - thanks! (It turned out that it was the FileReader I wasn't understanding correctly instead)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.