0

I try to upload file with below simple code , but i get error:

$("#register_to_buy_card").submit(function (event) {
        event.preventDefault();
        var $this = $(this);
        var url = $this.attr('action');
        var form = document.forms.namedItem($this);
        var formdata = new FormData(form);
        $.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            data: formData,
            success: function (data) {

            },
            error: function (data) {

            }
        });
    });

I get this error:

TypeError: Argument 1 of FormData.constructor is not an object.
var formdata = new FormData(form);

HTML:

<form id="register_to_buy_card" enctype="multipart/form-data" accept-charset="UTF-8" action="http://localhost/sample/registerToBuyCard" method="POST">

    <label for="passport">Passport Image</label>
    <input type="file" name="passport">
    <div class="checkbox">
    <button class="btn btn-default" type="submit">Submit</button>

</form>

2 Answers2

2

The error you are getting is because:

var form = document.forms.namedItem($this);

namedItem expects a string. You are passing it var $this = $(this);, which is a jQuery object.

this is already a form object. So change:

    var $this = $(this);
    var url = $this.attr('action');
    var form = document.forms.namedItem($this);
    var formdata = new FormData(form);

to

var formdata = new FormData(this);

(Yes, those four lines should be replaced with a single line).


Then see this other question which covers the issues not directly related to your error message.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

The issue is the element passed in the FormData is not the form but a jQuery object. You need to put the form which is this in the context.

You need to update this:

var formdata = new FormData(this);

and use :

contentType:false,
processData:false,

in the ajax options.


Updated code should be:

$("#register_to_buy_card").submit(function (event) {
    event.preventDefault();
    var url = $(this).attr('action');
    var formdata = new FormData(this);  // <--------update with 'this'
    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: formData,
        contentType:false,   //<-----------required
        processData:false,   //<-----------required
        success: function (data) {

        },
        error: function (data) {

        }
    });
});
Jai
  • 74,255
  • 12
  • 74
  • 103