Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP not receiving formData object from ajax

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.

like image 955
xdl Avatar asked Jul 19 '26 10:07

xdl


1 Answers

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.

like image 164
Musa Avatar answered Jul 20 '26 23:07

Musa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!