SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    Web
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    JavaScript File Upload Progess Indication

    I have made a dynamic dropdown file upload system where user can choose the engineering stream, then the semester and then subject, and the file gets uploaded in the desired directory. This works fine normally. I came across the Javascript/AJAX File Upload Progress tutorial from PHPAcademy, things worked fine until I got stuck into this.

    Without adding the javascript file (for upload progress), the files get uploaded in the correct directory, show no errors in the firebug, and also gives the link to the file after it gets uploaded.

    But after I add the JS file, the link doesn't come after upload, it gets uploaded in the root directory always, it shows the progress though, and the console shows two errors.

    Here is my PHP code:
    PHP Code:
    <?php

        
    if(isset($_POST['upload']))   { 
          
    $path1=$_POST['one']."/"
          
    $path2=$_POST['two']."/"
          
    $path3=$_POST['three']."/";   
          
    $upload_path=$path1.$path2.$path3;
        }
        else  {
              echo 
    "Follow the instructions before uploading a file";
        }    

        if(!empty(
    $_FILES['file'])) {
            foreach(
    $_FILES['file']['name'] as $key => $name) {
                if(
    $_FILES['file']['error'][$key]==&& move_uploaded_file($_FILES['file']['tmp_name'][$key], $upload_path."$name")) {
                    
    $uploaded[] = $name;
                }
            }
            if(!empty(
    $_POST['ajax'])) {
                die(
    json_decode($uploaded));
            }   
        }  
    ?>
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta http-equiv="content-type" content="text/html; charset=UTF-8">
            <title> SRMUARD - Upload </title>
            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
            <script type="text/javascript" src="upload.js"></script>        
            <script type="text/javascript">
                function val()
                {
                    if(document.uploads.three.selectedIndex == 0)
                    {
                        alert("Please choose all the appropriate options");
                    }
                }
            </script>   
            <script>
                $(function() {
                    $("#text-one").change(function() {
                    $("#text-two").load("textdata/" + $(this).val() + ".txt");
                    });
                    $("#text-two").change(function() {
                    $("#text-three").load("textdata/" + $(this).val() + ".txt");
                    });
                });
            </script>
        </head>
        <body>
            <div value="<?php $upload_path ?>" id="uploadpath"></div>
            <div id="uploaded">
                <?php
                    
    if(!empty($uploaded)) {
                        foreach(
    $uploaded as $name) {
                            echo 
    'File Link: '.'<a href="' $upload_path $name '" >'$name'</a><br/>';
                        }
                    }
                
    ?>
            </div>
            <div id="upload_progress" style="display: none"></div>
            <div>
                <form action="" method="POST" enctype="multipart/form-data" name="upload" id="upload">
                    <label for="file">Choose a file: </label><br/>
                        <input type="file" name="file[]" id="file" multiple="multiple"><br/><br/>               
                        <select id="text-one" name="one">                   
                            <option selected value="base">Select Department</option>
                            <option value="CSE" name="cse">Computer Science Engineering</option>
                            <option value="ECE" name="ece">Electronics & Communication Engineering</option>
                            <option value="MECH" name="mech">Mechanical Engineering</option>                        
                        </select><br/><br/> 
                        <select id="text-two" name="two"> //Displays options dynamically using text files
                            <option>Select Semester</option>
                        </select><br/><br/>                  
                        <select id="text-three" name="three"> //Displays options dynamically using text files
                            <option>Select Subject</option>
                        </select><br/><br>  
                        <input type="submit" name="upload" id="submit" value="Upload" onClick="val()" />        
                </form>
            <div>
        </body>
    </html>
    Here is my JS file:

    Code:
    var handleUpload = function(event) {
    
        event.preventDefault();
        event.stopPropagation();
    
        var fileInput = document.getElementById('file');
    
        var data = new FormData();
    
        data.append('ajax', true);
    
        for(var i = 0; i < fileInput.files.length; ++i) {
            data.append('file[]', fileInput.files[i]);
        }
    
        var request = new XMLHttpRequest();
    
        request.upload.addEventListener('progress', function(event) {
            if(event.lengthComputable) {
    
                var percent = event.loaded / event.total;
                var progress = document.getElementById('upload_progress');
    
                while(progress.hasChildNodes()) {
                    progress.removeChild(progress.firstChild);
                }
    
                progress.appendChild(document.createTextNode(Math.round(percent * 100) + '%'));
            }
        });
    
        request.upload.addEventListener('load', function(event) {
            document.getElementById('upload_progress').style.display = 'none';
        });
    
        request.upload.addEventListener('error', function(event) {
            alert('Upload failed due to some reason!');
        });
    
    
    
        request.addEventListener('readystatechange', function(event) {
            if(this.readyState == 4) {
                if(this.status == 200) {
    
                    var links = document.getElementById('uploaded');
                    var uploaded = eval(this.response);
                    var div, a;
                    var phpval = document.getElementById('uploadpath').value;
                    for(var i=0; i < uploaded.length; ++i) {
                        div = document.createElement('div');
                        a = document.createElement('a');
                        a.setAttribute('href', phpval + uploaded[i]);
                        a.appendChild(document.createTextNode(uploaded[i]));
                        div.appendChild(a);
                        links.appendChild(div);
                    }
    
                } else {
                    console.log('Server replied with HTTP status ' + this.status);
                }
            }
        });
    
        request.open('POST','upload.php');
        request.setRequestHeader('Cache-Control','no-cache');
    
        document.getElementById('upload_progress').style.display = 'block';
    
        request.send(data);
    
    }
    
    window.addEventListener('load',function(event) {
        var submit = document.getElementById('submit'); 
        submit.addEventListener('click', handleUpload);
    });
    For the demo, you can refer this link, things will be more precise, please turn on your firebug console and check the errors and help me. I am not able to solve this.

    http://ankursinha.net/ARD/upload.php

    Thank You

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,608
    Mentioned
    24 Post(s)
    Tagged
    1 Thread(s)
    Testing your page the first error I get is:

    Unhandled Error: Cannot convert 'document.uploads' to object
    if(document.uploads.three.selectedIndex == 0)

    in function val()

    Second error:

    Unhandled Error: at index 7: expected ';', got 'the'

    in upload.js on the statement assigning this.response to uploaded

    The script ceases running at that point.

    Note that the code to actually do the data_append of the files has not run yet - it is still processing the response from the ajax call triggered by data.append('ajax', true);
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Enthusiast
    Join Date
    Nov 2012
    Location
    Web
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So how do I get rid of these two problems, I am not good with JavaScript

  4. #4
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,354
    Mentioned
    179 Post(s)
    Tagged
    9 Thread(s)
    Hi,

    when I try and upload a file I get:

    Code:
    Uncaught TypeError: Cannot read property 'three' of undefined - upload.php:13
    This is caused by the following code, where document.uploads is undefined.

    Code JavaScript:
    function val(){
      if(document.uploads.three.selectedIndex == 0){
        alert("Please choose all the appropriate options");
      }
    }

    It is undefined, because your form has a name attribute of "upload" not "uploads".

    You need to change it to:

    Code JavaScript:
    if(document.upload.three.selectedIndex == 0){


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •