-1

How do you pass both text input as well as a file in one jQuery AJAX call? The code I have below passes the text input fields well but the file input returns an error (see below).

var formData = new FormData();

    formData = {
        'name'              : $('input[name=name]').val(),
        'email'             : $('input[name=email]').val(),
        'superheroAlias'    : $('input[name=superheroAlias]').val()
    };

    formData.append('profile_pic', $('input[id="profile_pic"]')[0].files[0]);

    // process the form
    $.ajax({
        type        : 'POST', 
        url         : 'process.php', 
        data        : formData,
        dataType    : 'json',
        processData : false,
        contentType : false,
        encode      : true
    })

On trying to receive the request on the PHP end like this:

$target_dir = "image_uploads/";
$target_file = $target_dir .rand(1,999). basename(str_replace(" ","",$_FILES["profile_pic"]["name"]));

I get the following error:

Undefined index: profile_pic

I have checked out a couple of solutions here on Stack Overflow already but none has done the trick for me yet.

How can I resolve this?

RayMan
  • 93
  • 1
  • 1
  • 10
  • https://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php Duplicated question. – Cosmin_Victor Nov 15 '17 at 08:56
  • Possible duplicate of [jQuery AJAX file upload PHP](https://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php) – Cosmin_Victor Nov 15 '17 at 08:57
  • formData.append('name', $('input[name=name]').val()) formData.append('email', $('input[name=email]').val()) formData.append('superheroAlias', $('input[name=superheroAlias]').val()) – bipin patel Nov 15 '17 at 08:59
  • Shouldn't you set somewhere the enctype to "multipart/form-data"? – Amarnasan Nov 15 '17 at 09:00
  • @Amarnasan, the form already has that parameter – RayMan Nov 15 '17 at 09:52
  • Sorry, can't see that parameter used in your code. – Amarnasan Nov 15 '17 at 09:55
  • @Cosmin_Victor, the example you reference only includes the file, mine is a mix of both file and text fields – RayMan Nov 15 '17 at 09:59
  • @Amarnasan, You're totally right. I can't believe I spent hours thinking I had already done that bit. I've simply added this: formData.append('profile_pic', $('input[type=file]')[0].files[0]); and it now works. If you want, you can put your comment as a solution and I'll mark it as the correct one. Thanks! – RayMan Nov 15 '17 at 10:10

1 Answers1

0

Just bind submit listener for your form and pass form data to your ajax automatically like below:

$('#form').submit(function(e){
    e.preventDefault();
    var formData = new FormData(this); 

    $.ajax({
        type        : 'POST', 
        url         : 'process.php', 
        data        : formData, 
        processData : false,
        contentType : false,
        encode      : true
    })

})
gkatiforis
  • 1,588
  • 9
  • 19