0

I'm making a very simple file upload web application, i tested it with a simple POST request directly to the PHP page and it works fine but not with Ajax. I'm thinking it's related to the way i'm using FormData() but i did google and experiment with other solutions using the FormData but none of them worked so i'm not entirely sure where the problem lies. I just get this type of error in the console :

Object { readyState: 0, getResponseHeader: getResponseHeader(key), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(name, value), overrideMimeType: overrideMimeType(type), statusCode: statusCode(map), abort: abort(statusText), state: state(), always: always(), catch: catch(fn), … }

HTML :

     <form id="upForm" enctype="multipart/form-data">
        <input hidden name="MAX_FILE_SIZE" value="3000000">
        <input id = "file" type="file" name="file"> <br>
        <input type="submit" value="upload">
    </form>

JS script :

$(document).ready(function (e) {
    $("#upForm").on('submit', function (e) {
        $.ajax(
            {
                type: 'POST',
                dataType: 'JSON',
                url: '/data/controls.php',
                processData: false,
                contentType: false,
                cache: false,
                data: new FormData(this),
                // beforeSend: // TO-DO
                success: function (response) {
                    // file uploaded
                    console.log(response);
                },
                error: function (response) {
                    console.log(response)
                }
            }
        )
    }
    )
}
)

controls.php :

$uploadDir = "../upload/";
$response = array(
    'status' => 0,
    'message' => 'Oops!'
);

if ($_SERVER["REQUEST_METHOD"] == "POST"){
    //test file extension
    //test file size
    if ($_FILES['file']['size'] > 3000000){
        $response['status'] = 0;
        $response['message'] = 'File size too big!';

    } else {
        $allowedTypes = array('jpg', 'png', 'jpeg', 'gif');
        $fileName = basename($_FILES['file']['name']);
        $filePath = $uploadDir . $fileName;
        $fileType = pathinfo($filePath, PATHINFO_EXTENSION);

        if (in_array($fileType, $allowedTypes)){
            if(move_uploaded_file($_FILES['file']['tmp_name'], $filePath)){
                $response['status'] = 1;
                $response['message'] = 'Something went wrong :(';
            }
        } else {
            $response['status'] = 2;
            $response['message'] = 'File format not allowed!';
        }
    }
    if ($response['status'] = 1){
        $PDOinst= DBconnect::getInstance();
        $PDO = $PDOinst->getConnection();
        $sqlString = "INSERT INTO fileUpload values (NULL, :fname, :size, :upDate)";
        $query = $PDO->prepare($sqlString);
        $paramArray = array(
            'fname' => $_FILES['file']['name'],
            'size' => $_FILES['file']['size'],
            'upDate' => date("d-m-Y (G:i)")
        );
        $query->execute($paramArray);
        $response['status'] = 3;
        $response['message'] = 'File uploaded successfully!';
    }
    echo json_encode($response);
}

echo json_encode($response);
cybercivizen
  • 79
  • 1
  • 7
  • 1
    This won't even be using AJAX - you didn't tell javascript to prevent the postback (with e.preventDefault()). So it will just submit the form and the Javascript will get stopped in its tracks at that point, because the browser discards the current page. – ADyson Feb 12 '21 at 13:41
  • You need to call `e.preventDefault()` in the submit handler to prevent the standard form submission – Rory McCrossan Feb 12 '21 at 13:41
  • Beyond that, there are examples of doing file uploads with jQuery/AJAX in a few places online already, including older questions here. I'm assuming you maybe attempted to copy from those already. So the rest of your code you can check against those examples. But it looks like you're probably on the right lines. – ADyson Feb 12 '21 at 13:43
  • Does this answer your question? [jQuery AJAX file upload PHP](https://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php) – Alex Berger Feb 12 '21 at 13:51
  • No unfortunately it does not, adding e.preventDefault() doesn't make much difference apparently. – cybercivizen Feb 12 '21 at 14:04
  • 1
    EDIT : actually yes it does answer my question sorry and thanks ! – cybercivizen Feb 12 '21 at 14:09

1 Answers1

0

Please add this 2 line in ajax function enctype: 'multipart/form-data', mimeType: 'multipart/form-data',

$.ajax(
                {
                    type: 'POST',
                    dataType: 'JSON',
                    url: '/data/controls.php',
                    processData: false,
                    contentType: false,
                    enctype: 'multipart/form-data',
                    mimeType: 'multipart/form-data',
                    cache: false,
                    data: new FormData(this),
                    // beforeSend: // TO-DO
                    success: function (response) {
                        // file uploaded
                        console.log(response);
                    },
                    error: function (response) {
                        console.log(response)
                    }
                }
            )
Paras Raiyani
  • 748
  • 5
  • 10
  • What does this do exactly? I already fixed it by adding e.preventDefault() as suggested by some members, so i'm kinda curious about this approach. – cybercivizen Feb 13 '21 at 19:50