Sunday, February 1, 2015

how to upload csv file to server via ajax in javascript


how to upload csv file to server via ajax in javascript




dropContainer.addEventListener('drop',function(evt){
    evt.stopPropagation();//stop event bubble
    evt.preventDefault(); // stop event bubble
    //iterate through the files
    Array.prototype.forEach.call(evt.dataTransfer.files, function (currentData) {
        //currentData - File - current file object of evt.dataTransfer.files
        filereader = new FileReader; // create a file reader
        //define when load ends listener
        filereader.onloadend = function(){
            contenArea.innerHTML += filereader.result;
        }
        filereader.readAsText(currentData);//start reading the file

      //=====   IF you want to send the form data to server ===
        // create a form data , you can retrieve the file in  PHP    via  $_FILES['uploadedFile']
        var tempFormData = new FormData;
        tempFormData.append("uploadedFile", currentData);
        // prepare ajax content and sendfile
        xhr = new XMLHttpRequest();
         //gets called everytime there is a state change
        xhr.onreadystatechange = function () {
            if (xhr.status === 4) {
                console.log("done uploading");
            }
        };
         // configure the xhr
        xhr.open("POST", "http://localhost:8000");
        // send the form data
        xhr.send(tempFormData);
    });

});

evt.dataTransfer.files are NOT ARRAYS

 Today I have learned that evt.dataTransfer.files are not Arrays , they are Objects
And to iterate through them you must call

Array.prototype.forEach

So I was doing my homework today and to my suprise , I got an error iterating over evt.dataTransfer.files .  Like what in the world is going on . Turns out , its not an array its an Object . TO iterate through them you must use Array.prototype.forEach.call . Good thing Ive watched the
TutsPlus - JavaScript Fundamentals 101  . A life saver ,.


dropContainer.addEventListener('drop',function(evt){
    evt.stopPropagation();
    evt.preventDefault();
    Array.prototype.forEach.call(evt.dataTransfer.files, function (currentData) {
        alert(currentData.name);
    });
    filereader = new FileReader;
    filereader.onload = function(){

    }
    //read the files
    // prepare ajax content
});