0

I am trying to test a simple FormData object but its not working at all. jsfiddle: https://jsfiddle.net/8j80898h/

html code:

<form id="createForm" name="createForm" novalidate enctype="multipart/form-data">
    <input type="hidden" name="name" value="Name1" />
    <input type="file" name="file" />
    <input type="button" id="submitIt" value="Submit" />
</form>

js:

$(document).ready(function() {
    $('#submitIt').click(function() {
        var fd =  new FormData($('#createForm')[0]);
        fd.append( 'name', $('input[name=name]').val());

        $.ajax({
            url: url,
            data: fd,
            processData: false,
            contentType: false,
            type: 'POST',
            success: function(data){                    
                alert(data);
            }
        });
    });
});

Server is always getting null values for name and file

coure2011
  • 34,326
  • 71
  • 200
  • 319

2 Answers2

2

FormData has a get method you should use:

$(document).ready(function() {
    $('#submitIt').click(function() {
        var d = new FormData($('form')[0]);        
        alert(d.get('name'));
    });
});

read more in MDN: https://developer.mozilla.org/en-US/docs/Web/API/FormData/get

MoLow
  • 2,990
  • 2
  • 17
  • 39
0

rather than making an FormData object you can access elements within an form like the code below shows :)

$(document).ready(function() {
  $('#submitIt').click(function() {
    var d = $('form').toArray();        
    alert(d[0].name);
  });
});
Roy James Schumacher
  • 636
  • 1
  • 11
  • 27