0

I've a form to upload a file and an input.

<form id="form">
    <input type="text" id="name">
    <input type="file" id="file">
</form>

This is what I'm using to send the file in Ajax:

$('#form').submit(function(e){
    e.preventDefault();
    var file_data = $('#file').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);

    $.ajax({
        type : 'POST',
        data: form_data,                         
        url: 'upload.php',
        dataType: 'text',
        cache: false,
        contentType: false,
        processData: false,
        ...

But I dont get the input value.

What I'm missing here please ?

Thanks.

1
  • You would need another append() for the text input key and value Commented Aug 19, 2020 at 0:55

1 Answer 1

1

It's simpler to pass the whole form element into FormData() than manually append to it when you need all the data from that form

Instead of:

var file_data = $('#file').prop('files')[0];   
var form_data = new FormData();                  
form_data.append('file', file_data);

Just do:

var form_data = new FormData(this);// `this` is the form element submit event occured on

And add name attributes to the form controls:

<form id="form">
    <input name="name" type="text" id="name">
    <input name="file" type="file" id="file">
</form>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, and the I can get the file in PHP like this $_FILES['file']['name'] or like this $_POST['file']['name'] ?
No...$_FILES['file'] and $_POST['name']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.