Ajax POST request via jQuery and FormData - $_POST empty on PHP

天大地大妈咪最大 提交于 2019-12-01 01:47:04

问题


I wish to upload an image to the server via ajax using jQuery and FormData.

My jQuery code is as follows

var formData = new FormData("form")[0];
  var fileName = $("#InputLogo")[0].files[0].name;

  $.ajax ( {
      url : 'upload.php',
      type : 'POST',
      data : { "data" : formData, "fileName" : fileName },
      processData : false,
      success : function(data) {
          console.log(data);
          alert(data);
      }
  });

This code is called when the user selects a new file to upload.

MY server backend is PHP and it handles the request as follows

$data = $_POST['data'];
$fileName = $_POST['fileName'];
$fp = fopen('/img/'.$fileName, 'w');
fwrite($fp, $data);
fclose($fp);
$returnData = array("data" => $data);
print_r($_POST);

The POST request does occur, but $_POST remains empty.

I tried searching for the solution but couldn't find an exact one.

Any suggestions would be appreciated.

EDIT : Here is the form in HTML

<form id=card-form" method="post" action="" >
      <div class="form-group">
    <label for="InputName">Name of the Company</label>
    <input type="text" class="form-control" id="InputName" placeholder="Enter a name">
    </div>
    <div class="form-group">
    <label for="InputEmail">Email</label>
    <input type="email" class="form-control" id="InputEmail" placeholder="Enter email">
    </div>
    <div class="form-group">
    <label for="InputLogo">Choose a company logo</label>
    <input type="file" id="InputLogo" accept="image/*">
    <p class="help-block">For good visibility, please limit the image to 200 x 200 px</p>
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>

回答1:


The FormData() constructor isn't a selector engine and it doesn't represent an Array-like collection, so var formData is likely equal to undefined.

To use it, you'll have to find the <form> first and pass it to the constructor:

var form = $('form')[0];
var formData = new FormData(form);

If the <input type="file"> is within the <form>, it should already be included in formData. But, if it isn't, you can also .append() it:

var inputLogo = $("#InputLogo")[0];
formData.append(inputLogo.name, inputLogo.files[0]);

And, set formData as the data being sent, telling jQuery not to assume a contentType for it:

// ...
    data : formData,
    contentType : false,
    processData : false,
// ...

Then, the fileSize should be available in PHP's $_FILES collection:

$fileName = $_FILES['inputLogo']['name'];



回答2:


I know this is an old post, but I came across it when trying to solve an analogous problem for myself, and none of the replies pointed this issue out, so I am posting a reply in case someone else finds him/herself in the same situation.

It turns out that, as documented in another StackOverflow post:

Does form data still transfer if the input tag has no name?

if you do not have a non-empty name attribute for your file input element, no data from that element will be sent in a request.

So your input element:

<input type="file" id="InputLogo" accept="image/*">

Should be:

<input type="file" id="InputLogo" accept="image/*" name="yourfieldnamehere">

or the file will not be sent with the form data.




回答3:


I too tried a lot with the following ways:

var formData = new FormData("form")[0];
var formData = new FormData("form");
var formData = new FormData($('form-id'));
var formData = new FormData(this);

None of them worked for me. But at last, I used a javascript way of getting elementById, and it worked perfectly.

formdata = new FormData(document.getElementById('form_id'))

Usually in request headers you will find an encrypted text like the one given below: multipart/form-data; boundary=----WebKitFormBoundaryUuVvGDydAdTf3Bmp

And when you try to alert the form data it will show [object formdata]. This means that the formdata function is working fine.

When you return the values of $_POST, $_REQUEST or $_FILES, and if it is blank, it would mean that formdata is not able to access the form element provided. So first you have to confirm that formdata is able to access the form element or not, and then try other possibilities.




回答4:


well there are few thigns you need to consider while using formData with ajax..and you can append data to FormData using append() method of FormData.

try this..

 var formData = new FormData("form")[0];
 formData.append("fileName",$("#InputLogo")[0].files[0].name);

 $.ajax ( {
   url : 'upload.php',
   type : 'POST',
   data : formData ,
   processData : false,
   processData: false,  // tell jQuery not to process the data
   contentType: false   // tell jQuery not to set contentType
   success : function(data) {
      console.log(data);
      alert(data);
   }
});

reference




回答5:


One problem is that fileuploads via Ajax don't work unless you use some HTML5 advantages.

Here is a goo post describing it: How can I upload files asynchronously?




回答6:


Hello @panx sorry for the late response i had the same problem but without using Jquery, i solved it by removing any headers from my ajax request. So remove any RequestHeaders commented them out and try again if you still have that problem.



来源:https://stackoverflow.com/questions/20375461/ajax-post-request-via-jquery-and-formdata-post-empty-on-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!