file upload with formData returns undefined file array

3.1k Views Asked by At

im getting undefined from print_r($_POST), it's posting on the same php page.

Array ( [file] => undefined )

Edited - added part where it calls the upload_banner function

HTML

<form enctype="multipart/form-data" id="banner_form" class="form-horizontal" role="form" action="">
  <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
  <input id="file" name="file" type="file" class="filestyle" accept="image/jpeg,image/gif,image/png">
</form>

JS

$('#submit_btn').click(function(e){
    e.preventDefault();

    var date = document.getElementById('datepicker').value;
    var title = document.getElementById('title').value;
    var content = document.getElementsByClassName('note-editable')[0];

    if(date == "" || title == "") {
      alert("Please fill in the required fields");
      return false;
    }
    else {

        var cfm = confirm("Confirm Submit Changes?");
        if(cfm === true)
        {

          var editarea = content.innerHTML;

          $.post ("functions/add_upcoming.php",{date: date,title: title,sm_content: editarea},
            function(data) {
          });

          upload_banner();
        }
        else
        {
          return false;
        }
      }
  });




function upload_banner() {
    var form_data = new FormData($('#banner_form')[0]);
    form_data.append('file', $('input[type=file]')[0].files[0]);

      $.ajax({
        url: "upcomingevents.php?p=73",
        contentType: false,
        processData: false,
        dataType: 'json',
        data: form_data, 
        type: 'post',
        success: function(data) { },
        contentType: false,
        processData: false
    });
}

json as datatype cause im returning arrays from php side, did not post additional code cause im already getting issue at the file upload part

PHP

if(isset($_POST['file'])) {
  print_r($_POST);
  exit();
}

am i doing anything wrong here?

2

There are 2 best solutions below

2
On BEST ANSWER

You're function isn't even being called considering you don't have the submit button for the handler to run. It should be like:

<form enctype="multipart/form-data" id="banner_form" class="form-horizontal" role="form" action="">
  <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
  <input id="file" name="file" type="file" class="filestyle" accept="image/jpeg,image/gif,image/png">
  <input type="submit" id="submit_btn"/>
</form>

Also you have a syntax error in your JS, there is no need for the second set of }); to close the click handler.

JSFiddle: https://jsfiddle.net/sggf82am/2/

4
On

The FormData is set up incorrectly, should be :

var form_data = new FormData( );
form_data.append('file', $('input[type=file]')[0].files[0]);

Are you sure the url refered by the ajax is correct?

Why is there query param (?p=73) as you're doing post and not get.

Finaly, try to print the response through

success: function(data) { alert(JSON.stringify(data))},