Ajax data not being displayed after upload

Viewed 59

Currently my entire code is working almost flawlessly, how ever upon upload the ajax data is not being displayed on my webpage after a successful upload.

Below is the code I am using (completely) because I am rather new and have been reviewing various stack over flow posts to guide me in building this.

Sorry for lack of structure below.. I don't know how to adapt to stack overflows structure requirements..

The actual form input / submit

<form action="upload2.php" class="upload" enctype="multipart/form-data" id="upload" method="post" name="upload">
    <fieldset>
        <legend>Uplaod Files</legend> <input id="file" multiple name="file[]" required="" type="file"> <input id="submit" name="submit" type="submit" value="upload">
    </fieldset>
    <div class="bar">
        <span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt"></span></span>
    </div>
    <div class="uploads" id="uploads"></div>
</form>

Here's the PHP code I am using to upload the file.

<?
header('Content-Type: application/json');

$upload = [];
$allowed = ['mp3', 'm4a'];

$succeeded = [];
$failed = [];

if (!empty($_FILES['file'])) {
    foreach ($_FILES['file']['name'] as $key => $name) {
        if ($_FILES['file']['error'][$key] === 0) {
            $temp = $_FILES['file']['tmp_name'][$key];
            $file_name = $_FILES['file']['name'][$key];
            $file_size = $_FILES['file']['size'][$key];

            $ext = explode('.', $name);
            $ext = strtolower(end($ext));
            $s = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 4)), 0, 4);
            $file = $s . '.' . $ext;
            $data = $file_name . PHP_EOL . $file_size;
            file_put_contents('d/' . $s . '.txt', $data);
            if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "v/{$file}") === true) {
                $succeeded[] = array(
                    'name' => $name,
                    'file' => $file,
                );
            } else {
                $failed[] = array(
                    'name' => $name
                );
            }
        }
    }
    if (isset($_POST['ajax'])) {
        echo json_encode(array(
            'succeeded' => $succeeded,
            'failed' => $failed
        ));
    }
}

Below is javascript event listener + the returned data from ajax

document.getElementById('submit').addEventListener('click', function (e) {
    e.preventDefault();
    var f = document.getElementById('file'),
        pb = document.getElementById('pb'),
        pt = document.getElementById('pt');
    app.uploader({
        files: f,
        progressBar: pb,
        progressText: pt,
        processor: 'upload2.php',
        finished: function (data) {
            var uploads = document.getElementById('uploads'),
                succeeded = document.createElement('div'),
                failed = document.createElement('div'),
                anchor,
                span,
                x;
            if (data.failed.length) {
                failed.innerHTML = '<p>file didnt upload<\/p>';
            }
            uploads.innerText = '';
            for (x = 0; x < data.succeeded.length; x = x + 1) {
                anchor = document.createElement('a');
                anchor.href = 'uploads/' + data.succeeded[x].file;
                anchor.innerText = data.succeeded[x].name;
                archor.target = '_blank';
                console.log(anchor);
                succeeded.appendChild(anchor);
            }
            uploads.appendChild(succeeded);
        },
    });
});

Below is the javascript we're using for ajax (I think the issue is here but I keep reviewing it and I'm not able to find the problem.)

var app = app || {};
(function (o) {
    "use strict";
    var ajax, getFormData, setProgress;
    ajax = function (data) {
        var xmlhttp = new XMLHttpRequest(),
            uploaded;
        xmlhttp.addEventListener('readystatechange', function () {
            if (this.readystate === 4) {
                if (this.status === 200) {
                    uploaded = JSON.parse(this.response);
                    if (typeof o.options.finished === 'function') {
                        o.options.finished(uploaded);
                    }
                } else {
                    if (typeof o.options.error === 'function') {
                        o.options.error();
                    }
                }
            }
        });
        xmlhttp.upload.addEventListener('progress', function (event) {
            var percent;
            if (event.lengthComputable === true) {
                percent = Math.round((event.loaded / event.total) * 100);
                setProgress(percent);
            }
        });
        xmlhttp.open('post', o.options.processor);
        xmlhttp.send(data);
    };
    getFormData = function (source) {
        var data = new FormData(),
            i;
        for (i = 0; i < source.length; i = i + 1) {
            data.append('file[]', source[i]);
        }
        data.append('ajax', true);
        return data;
    };
    setProgress = function (value) {
        if (o.options.progressBar !== undefined) {
            o.options.progressBar.style.width = value ? value + '%' : 0;
        }
        if (o.options.progressText !== undefined) {
            o.options.progressText.innerText = value ? value + '%' : '';
        }
    };
    o.uploader = function (options) {
        o.options = options;
        if (o.options.files !== undefined) {
            ajax({});
            ajax(getFormData(o.options.files.files));
        }
    }
}(app));

My file is uploading, the progress bar is working and without returning e.preventDefault(); when it redirect to upload2.php I'm able to see the contents of the json i really don't know what my problem could be..

1 Answers

First of all, you have a typo in anchor here:

archor.target = '_blank';

Maybe this throws error and stops other code execution

Also you could check if your uploads div is visible via element inspector in browser.

If console.log shows nothing - do you mean by this it is not even called or it shows undefined? If it doesn't show at all, then look into the for that uses data.succeeded.length param as a limit - maybe it equals 0 and thus console.log is never called

Related