1

I'm trying to upload a single file with JQUERY AJAX. I found this old thread - Jquery ajax single file upload

I followed the codes, but I kept getting the "Not Set" error on my php script.

Here's my HTML

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File:</label>
    <input type="file" name="file" required />
</form>
<input type="button" id="upload" value="Upload"></input>
<div id="output"></div>

Here's my Jquery code. I used latest uncompressed CDN - https://code.jquery.com/jquery-3.3.1.js

$( document ).ready(function() {

    $('#upload').on('click', function(){ 

                var formData = new FormData(); 
                formData.append('file', $('input[type=file]')[0].files[0]);
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: formData,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

Here's my php script (upload.php)

<?php
    if(isset($_GET['file'])){
    $filename = $_FILES['file']['name'];
        if(isset($filename) && !empty($filename)){
        echo 'File available';
        }else{
        echo 'please choose a file';
        }
    } else{
    echo 'No file';
    }
?>

Update: Changed my PHP code with below and it fixed the issue.

<?php
$info = pathinfo($_FILES['file']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "newname.".$ext; 

$target = 'files/'.$newname;
move_uploaded_file( $_FILES['file']['tmp_name'], $target);

if (file_exists("files/{$newname}")) {
echo "Uploaded!";
}
?>
MarlZ15199
  • 288
  • 2
  • 17

0 Answers0