JQuery1.8.0: Sending files from forms via AJAX

2019-08-29 03:18发布

I develop with CakePHP and initially thought this problem was Cake-related; it wasn't. I've re-written the question to make the answer I received more widely applicable

I have a form

  <form action"">
      <fieldset> 
      <!---- bunch of fields----->
      <input type="file" name="data[Upload][file]" id="UploadFile">
      <button id="ajaxUploadSubmit"> Submit </button>
      </fieldset>
  </form>

And the submit function I've written looks like:

$( "#ajaxUploadSubmit" ).click(function() {
                $.ajax({
                    url:"uploads/add",
                    data: $( "#UploadsAddForm" ).serialize()
                }).done(function(responseText) {
                    alert(responseText);
                  })
                 .fail(function() {
                     alert('failxors');
                  })
                });

But this line returns an empty array: $this->request->data.

2条回答
来,给爷笑一个
2楼-- · 2019-08-29 03:57

I'm only adding this answer so this question can be marked as answered; in fact thaJeztah answered this in the 3rd comment of Jai's answer: the problem, in this case, was that I should have been using FormData() instead of Serialize() as seen here: how to do file upload using jquery serialization

查看更多
该账号已被封号
3楼-- · 2019-08-29 03:58

I think you are not stopping the form to submit:

$( "#ajaxUploadSubmit" ).click(function(e) {
      e.preventDefault();

Instead of click try submit:

try changing this:

$( "#ajaxUploadSubmit" ).click(function() {

to this one:

$(".form").submit(function(e) {
    e.preventDefault();
查看更多
登录 后发表回答