1

I am uploading an image using FormData and having trouble passing additional parameter with it. I want all my ajax calls to land on the same script i.e. ajax.php and execute the part of the script based on the additional parameter passed.

My ajax call looks like this:

$(document).on('click', '#btn-banner-upload', function(){
    var file_data = $("#bannerUpload").prop("files")[0];   
    var form_data = new FormData();                  
    form_data.append("file", file_data);
    console.log(form_data);
     $.ajax({
                url: "../server/upload.php",    
                cache: false,
                contentType: false,
                processData: false,
                data: {"case":"bannerUpload","form_data":form_data},
                dataType: 'json',                         
                type: 'post'
     }).done(function(response){
        console.log(response);
        $('html').css('background', 'url('+response.path+') no-repeat center center fixed');
     }).fail(function(response){
        console.log(response);
     })
})

And my php script looks like this:

if($_POST['case'] == 'bannerUpload'){
    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
        echo '{"result": "ok", "path":"../server/uploads/' . $_FILES["file"]["name"].'"}';
    }
}

Unfortunately, I returns that $_POST['case'] is undefined.

Thanks you!

jacobdo
  • 1,605
  • 3
  • 15
  • 34

1 Answers1

1

To append some values to the exisiting form data. Just do like this

var form_data= new FormData();   
var key = 'xyz'; 
form_data.append( 'yourValue', key );

Also, Try removing the quotes for the case

Change this data: {"case":"bannerUpload","form_data":form_data},

to

data: {case:"bannerUpload",form_data:"form_data"},

Tip :

Also check the Networks tab in your console to make sure everything goes right

Community
  • 1
  • 1
Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63