2

I need some assistance please.

I am trying to create an ajax upload web app from scratch as a personal hobby. I was able to get the files to upload to my uploads folder successfully, but I just can't seem to get the uploaded links to appear under the upload box and stay there permanently even after refreshing the web page.

I keep getting this error message in the google chrome browser console:
Uncaught TypeError: Cannot read property 'length' of undefined

and it is pointing me to this line in the index.php:
for(x = 0; x < data.succeeded.length; x = x + 1) {

Also the google chrome console is marking this as (anonymous function) in the upload.js file:
o.options.finished(uploaded);

I had used some youtube videos as a guide, but I just can't seem to figure it out.

Kindly Help Me Please

This is the index.php code and below is the upload.php code also the upload.js code.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Uploader</title>
        <link rel="stylesheet" href="css/global.css">
    </head>
    <body>
        <form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
            <fieldset>
                <legend>Upload files</legend>
                <input type="file" id="file" name="file[]" required multiple>
                <input type="submit" id="submit" name="submit" value="Upload">
            </fieldset>

            <div class="bar">
                <span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt"></span></span>       
            </div>

            <div id="uploads" class="uploads">
                Uploaded file links will appear here.           
            </div>

            <script src="js/upload.js"></script>
            <script>

                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: 'upload.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>Unfortunately, the following failed:</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;
                                anchor.target = '_blank';

                                succeeded.appendChild(anchor);
                            }

                            for(x = 0; x < data.failed.length; x = x + 1 ) {
                                span = document.createElement('span');
                                span.innerText = data.failed[x].name;

                                failed.appendChild(span);
                            }

                            uploads.appendChild(succeeded);
                            upload.appendChild(failed);

                        },

                        error: function() {
                            console.log('Not working');
                        }
                    });
                });             
            </script>

        </form>
    </body>
</html>

Upload.php code

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

$uploaded = '';
$allowed = '';

$succedeed = '';
$failed = '';

if(!empty($_FILES['file'])) {
    foreach($_FILES['file']['name'] as $key => $name) {
        if($_FILES['file']['error'][$key] === 0) {

            $temp = $_FILES['file']['tmp_name'][$key];

            $ext = explode('.', $name);
            $ext = strtolower(end($ext));

            $file = md5_file($temp) . time() . '.' . $ext;          

                if(move_uploaded_file($temp, "uploads/{$file}") === true) {
                    $succedeed[] = array(
                        'name' => $name,
                        'file' => $file
                    );
                } else {
                    $failed[] = array(
                        'name' => $name
                    );
                }               
        }
    }

    if(!empty($_POST['ajax'])) {
        echo json_encode(array(
        'succedeed' => $succedeed,
        'failed' => $failed
    ));
    }   
}

This is the upload.js code

var app = app || {};

(function(o) {
    "use strict";

    //Private methods
    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(getFormData(o.options.files.files));
        }
    }

}(app));
  • You can get empty data if your $_POST['ajax'] is empty. In this case your PHP script return nothing. So you can get empty "data" variable. Check your request and response. So you can find where you are wrong. You can share request and response here to help us to find right answer. – Panoptik Apr 22 '15 at 11:14
  • http://stackoverflow.com/questions/24446281/passing-image-using-ajax-to-php/24446611#24446611 this may help you – AkshayP Apr 22 '15 at 11:20
  • @Panoptik I looked at the request and response like you said. I saw the Google chrome console is marking this line as (anonymous function) in the uploads.js file ...... o.options.finished(uploaded); ....... – Access Denied Apr 22 '15 at 11:32
  • @A.P. I looked at your link and the codes are very different. Kindly point out where I should be looking please. – Access Denied Apr 22 '15 at 11:36
  • @Panoptik Please forgive me but I am still a little lost. – Access Denied Apr 22 '15 at 11:39
  • @AccessDenied you should research your request/response in browser network tab (debug panel). Make sure your request sent proper data and continue debugging. As for anonymous function - that is OK when you using callbacks. Determine what is wrong? If your actual request is not as expected, so your problem is in javascript. If your request is OK than you should find some errors in your php code. As I haven't acccess to test it and cannot see request/response I can't help you. Sorry. – Panoptik Apr 22 '15 at 12:24
  • @Panoptik Thanks, syms showed me that I misspelt 'succedeed' in the index.php file below.....That resolved the issue. I am working on another issue and if it works out, I will post back here and mark this issue as resolved. – Access Denied Apr 22 '15 at 12:33

1 Answers1

1

I think the problem is due to if(move_uploaded_file($temp, "uploads/{$file}") === true) try if(move_uploaded_file($temp, "uploads/{$file}") == true)

and also check data.succedeed spell in index.php

syms
  • 413
  • 2
  • 12
  • That would be same as `if (move_uploaded_file($temp, "uploads/{$file}"))`. [move_uploaded_file](http://php.net/manual/en/function.move-uploaded-file.php) will return `true` or `false` anyway. – skobaljic Apr 22 '15 at 11:54
  • yeah right, but actually when you echo this it will return 1 or 0. so don't go for type just check value – syms Apr 22 '15 at 11:57
  • @syms OMG......I spelt 'succedeed' incorrectly......that was the issue all along......Thank you very much, but how can I get the files to continue to display in the div below the upload box, after a page refresh. Everytime I refresh the page the uploaded files that were displaying in the div below the upload box would disappear. Can you assist me with that issue as well please ? – Access Denied Apr 22 '15 at 12:16
  • its not possible to persists the data in variable after refresh for this you have to use cookies or localstorage for storing file names and append them in div on document ready if it is exists in localstorage or cookies. – syms Apr 22 '15 at 12:20
  • @syms Thank you, I will try the local store or creating a .appcache file so the application can be available offline to also automatically put copy on the local machine. I will let you know how this works. If it works I will mark this question as resolved. – Access Denied Apr 22 '15 at 12:28
  • Great for loacalstorage you can have a look at [link](http://www.w3schools.com/html/html5_webstorage.asp) – syms Apr 22 '15 at 12:31
  • @syms Thanks, also if you have time, can you visit my other question please, Thanks in advance. Link: http://stackoverflow.com/questions/29799315/display-selected-answers-at-the-end-of-a-multiple-choice-quiz?noredirect=1#comment47726913_29799315 – Access Denied Apr 22 '15 at 14:47
  • @syms I am having some issues implementing the localstorage......The website you gave me says name value pairs......but I don't have name value pairs on the code above......I have been working on this and researching other websites for about 8 hours now. Can you give me some insight as to how to implement localstorage in the code above please. – Access Denied Apr 22 '15 at 23:15
  • Yeah you can keep your variable as key and value as a value so you can get as a variable name from local storage also you can only put string so if you have object convert it into string using JSON.stringify – syms Apr 23 '15 at 03:21