Ajax file upload not being store in the directory

I’m in the process of building a function in uploading a file(CSV) using AJAX. This is just a rough code since that I’m working and currently following a tutorial. I’m using XAMPP for server side languages

After executing i’m getting an alert that displays (obect FormData) inside and aside from that, the uploads directory is empty after submitting the file. Project currently has three items. (Uploads Folder, index.php and upload.php)

enter image description here

HTML

<form method="post" enctype="multipart/form-data">
    <input id="file-uploading" type="file" name="fileUploading" />
    <button id="upload" value="upload">Upload</button>
</form>

JAVASCRIPT

$('#upload').on('click', function() {
    var file_data = $('#file-uploading').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);
    alert(form_data);                             
    $.ajax({
                url: 'upload.php', 
                dataType: 'text',  
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,                         
                type: 'post',
                success: function(){
                    console.log('success'); 
                }
     });
});

PHP (uploads.php)

<!doctype html>

<html>

<body>

<?php

    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error' . $_FILES['file']['error'] . '<br/>';
    }

    else {

        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);

    }
    
?>

</body>

</html>
  1. see http://php.net/manual/en/features.file-upload.php#114004 for a proper upload script example

  2. why is there HTML in your processing script?

That’s because you’re leaving (actually, reloading) the page before the XHR gets sent. A button inside a form behaves like an input with type="submit", and without a given action, the form just submits to the current page itself – the page reloads, and it looks like nothing happened (you can see the alert() though because it freezes the entire page). So you’ll have to .preventDefault() for the AJAX call to take place, like

$('#upload').on('click', function(event) {
  event.preventDefault()
  // etc.
})

There’s nothing wrong with your PHP AFAICT. The doctype and html / body tags are indeed unnecessary though, unless you want to use the same script as a no-JS fallback form action.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.