0

I'm using ajax/php to load files but I don't understand how to add other variable than the file in the ajax function.

HTML:

<html>
    <body>      
        Select image to upload:     
        <input type="file" name="fileToUpload" id="fileToUpload">       
        <button onclick="loadNewPicture('tomato')" id="upload">Upload</button>
    </body>
</html>

JAVASCRIPT:

function loadNewPicture(vegetable)
    {
        var file_data = $('#fileToUpload').prop('files')[0];     
        var form_data = new FormData();                                 
        form_data.append('file', file_data);

        $.ajax(
        {
            url: 'TEST.php',
            dataType: 'text',
            cache: false,
            contentType: false,
            processData: false,
            data: form_data + '&vegetable =' + vegetable ,                                               
            type: 'post',
         });
    }

PHP:

<?php

    if ( 0 < $_FILES['file']['error'] ) 
    {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else 
    {
        $vegetable = ($_POST["vegetable"]);
        move_uploaded_file($_FILES['file']['tmp_name'], 'image/test/' . $_FILES['file']['name']);
    }
?>

Of course, it does not work saying "Undefined index: file" Any idea how could I do?

Mishal
  • 450
  • 9
  • 27
Nob0dy
  • 1
  • 1
  • Does [this](https://stackoverflow.com/questions/34336172/how-to-pass-multiple-variables-through-ajax) answer your question? – Mishal May 24 '20 at 10:01
  • you could use a `FormData` object – Professor Abronsius May 24 '20 at 10:04
  • I might be wrong here, but your datatype you are posting is text, you then call a variable 'file' but no such variable has been posted, only vegetable has. – AlwaysConfused May 24 '20 at 10:04
  • Does this answer your question? [How to upload multiple files using PHP, jQuery and AJAX](https://stackoverflow.com/questions/19295746/how-to-upload-multiple-files-using-php-jquery-and-ajax) – Yassine CHABLI May 24 '20 at 10:04

1 Answers1

0

Of course, it does not work saying "Undefined index: file" Any idea how could I do?

Its because in your code name of the input[type='file'] is fileToUpload.

So change your PHP code to

<?php

    if ( 0 < $_FILES['fileToUpload']['error'] ) 
    {
        echo 'Error: ' . $_FILES['fileToUpload']['error'] . '<br>';
    }
    else 
    {
        $vegetable = ($_POST["vegetable"]);
        move_uploaded_file($_FILES['fileToUpload']['tmp_name'], 'image/test/' . $_FILES['fileToUpload']['name']);
    }
?>
Kunal Raut
  • 2,495
  • 2
  • 9
  • 25