I have the following HTML form for uploading a file (picture):

<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>

I use the following JavaScript/jQuery to send form data and a variable value to PHP script:

var variable1= 1;

$('#upload').on('click', function() {
    var file_data = $('#sortpicture').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);

                url: 'upload.php', // point to server-side PHP script 
                dataType: 'text',  // what to expect back from the PHP script, if anything
                cache: false,
                contentType: false,
                processData: false,
                data: {form_data, number: variable1},                         
                type: 'post',
                success: function(php_script_response){
                alert(php_script_response); // display response from the PHP script, if any

The PHP script (upload.php) looks like this:

if ( 0 < $_FILES['file']['error'] ) {
    echo 'Error: ' . $_FILES['file']['error'] . '<br>';
else {
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    $filename = $_FILES['file']['name'];
echo $filename;

When I run this code, PHP throws some undefined index errors. If I use only “data: form_data” in ajax request (without variable1), then the file uploads successfully, but I need to send the variable too. How can I do this?


You can also append the number key => value to to the form data as

form_data.append('number',  variable1);

Then in Ajax call

data: form_data,