0

This is my HTML code.I'm not using <form>

<input id="sortpicture" type="file" data-id="7" name="sortpic" multiple/>
<button id="upload">Upload</button>

Here is JS

jQuery('#upload').on('click', function() {
    var file_data = jQuery('#sortpicture').prop('files')[0];       
    var form_data = new FormData();                  
    form_data.append('file', file_data); 
    form_data.append('id', 7); // ---> If I send this only i'm able to access `id` in php. If include `file` not access id in php file.

    jQuery.ajax({
        url: 'upload.php',   
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'POST',
        success: function(response){        
        },
        error:function(e){
        }
    });

PHP file

$name = $_FILES['file']['name'];
//print_r($_FILES);
$id = $_POST['id'];    // Unable to get id.

How can I get id in php file.Any suggestions please.

JAAulde
  • 19,250
  • 5
  • 52
  • 63
Gowri
  • 1,832
  • 3
  • 29
  • 53
  • Have you looked at [Uploading both data and files in one form using Ajax?](http://stackoverflow.com/questions/10899384/uploading-both-data-and-files-in-one-form-using-ajax) –  Nov 04 '14 at 03:25
  • Your snippet should be working.. Kindly check your param headers in your browser. – Drixson Oseña Nov 04 '14 at 06:20

1 Answers1

-1

Based on the documentation, I believe you're close. Keep in mind that I have never used the FormData API :) But, if I am interpreting it correctly, it's looking for the "name" attribute.

jQuery('#upload').on('click', function() {
    var formData = new FormData(); 
    var inputData = $('this').find('input');
    var fileData = inputData.files[0];       

    formData.append('file', fileData); //wants name attribute here?//
    formData.append('id', 7);

    jQuery.ajax({
        url: 'upload.php',   
        cache: false,
        contentType: false,
        processData: false,
        data: formData,                         
        type: 'POST',
        success: function(response){        
        },
        error:function(e){
        }
    });
});
EternalHour
  • 8,308
  • 6
  • 38
  • 57
  • `form_data.append('sortpic', file); //wants name attribute here?//` — That would be `'sortpic'`. The code in the question uses `'file'` which is the name that code tries to read from in PHP. It doesn't matter what the field was called in the DOM, the data set is being constructed manually. – Quentin Nov 04 '14 at 07:36
  • It matters on the client side. Obviously if you are using the wrong selector the javascript is not going to work. I understand PHP sees it as ['file'], didn't dispute that. – EternalHour Nov 04 '14 at 07:49
  • The first argument of `append` is not a selector, its the name you are assigning the value (the second argument) to. – Quentin Nov 04 '14 at 08:47
  • `input` is undefined, so that will throw an exception – Quentin Nov 05 '14 at 09:07