2

I'm trying to extend this script with a file-upload form: Ajax Contact Form on GitHub After the successfull implementation of PHPMailer, I thought it would be fun to add a new file-upload form. But I do not get it to run.

I've added a new form field into the index.html:

<div class="form-group" id="file1-field">
    <label for="form-file1" class="col-lg-2 control-label">Dateianhang</label>
    <div class="col-lg-10">
        <input type="file" class="form-control" id="form-file1" name="form-file1">
    </div>
</div>

Afterwards I've added the contentType and processData lines into the *.js file.

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

In the last step I've added these lines into the php script:

if(is_array($_FILES)) {
    $mail->AddAttachment($_FILES['form-file1']['tmp_name'],$_FILES['form-file1']['name']); 
}

I have googled around and tryied everything, but I can't get any data out of it. The whole form script breaks.

I hope you can help me. Thanks in advance.

Aiko
  • 21
  • 3
  • Add `enctype='multipart/form-data'` in your input file – Mihai Feb 01 '16 at 19:52
  • Thank you for your help. But sorry, the error persists: http://imgur.com/4Id2pNn It just works as expected when I delete the contentType and processData lines. – Aiko Feb 01 '16 at 20:55
  • With this two lines, the whole form fields are going to marked red, although everything is filled correct (except email). – Aiko Feb 01 '16 at 21:02
  • How are you defining formData? – Quentin Feb 02 '16 at 10:42

1 Answers1

0

I found a solution:

Get the form data with this procedure solved my problem:

// get the form data
var fData = new FormData();
fData.append('name', $('input[name=form-name]').val());
fData.append('email', $('input[name=form-email]').val());
fData.append('subject', $('input[name=form-subject]').val());
fData.append('message', $('textarea[name=form-message]').val());
fData.append('file1', $('input[name=form-file1]')[0].files[0]);

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

Instead of:

         // get the form data
        var formData = {
          'name': $('input[name="form-name"]').val(),
          'email': $('input[name="form-email"]').val(),
          'subject': $('input[name="form-subject"]').val(),
          'message': $('textarea[name="form-message"]').val()
        };

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

Thanks for your help!

Aiko
  • 21
  • 3