-2

On one of the pages I allow user to upload multiple images to upload. Script works fine in Firefox however for sometime it doesn't work on chrome as it give following error

Uncaught TypeError: Cannot read properties of undefined (reading 'response')
at uploadComplete (UploadMultipleAlbumImages.js:79:52)

enter image description here

Complete code of this js file

var xhr, formData;
var url = baseURL + "admin/albums/UploadImageCropAuto";
var currentLoaderRef, currentTickerRef, fileCount = 0, uploadedFiles = 0, failedFiles = 0, files;
var fileGuids = [], fileNames = [];

$(document).ready(function () {

    $("input[type='file']").change(function () {
        if (parseInt(this.files.length) > 10) {
            alert("Please select maximum of 10 files.");
        }
        else {
            $('span[id*="Validation"]').html('');
            clearFileUploadFields();
            files = this.files;
            fileCount = 0;
            for (i = 0; i < files.length; i++) {
                uploadFile(files[i], url, files[i].name);
            }
            showProgress(this);
            console.log($("#FileGuid").val());
        }
    });
});

function showProgress(fileInput) {
    $("#submit").prop("disabled", true);
    currentLoaderRef = $(fileInput).parent().next().children("div.loader");
    currentTickerRef = $(fileInput).parent().next().children("div.checkmark-cover");
    currentLoaderRef.show();
    //$("progress").show();
}

function checkIfFileIsImage(fileType) {
    if (fileType.indexOf("image") == -1) {
        return true;
    }
    return false;
}

function uploadFile(file, url, originalFileName) {
    xhr = new XMLHttpRequest();
    formData = new FormData();
    xhr.open("POST", url, true);

    //Binding events to the request object
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete.bind(null, originalFileName), false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);

    xhr.onreadystatechange = getResponseFromServer(xhr);
    formData.append("albumImage", file);
    xhr.send(formData);
}


//Progress event
function uploadProgress(event) {
    if (event.lengthComputable) {
        //$(".percents").html(" " + ((event.loaded / event.total) * 100).toFixed() + "%");
        $("progress").val(((event.loaded / event.total) * 100));
    }
    else {
        alert("Failed to compute file upload length");
    }
}


function getResponseFromServer(xhr) {
    if (xhr.readyState == 4 && xhr.status == 200) {

    }
};

//Request complete event
function uploadComplete(originalFileName, event) {
    var response = JSON.parse(event.originalTarget.response);
    fileCount++;
    switch (response.messageType) {
        case "success":
            uploadedFiles++;
            fileGuids.push(response.fileName);
            fileNames.push(originalFileName);
            updateUploadedFilesUl(originalFileName, '', true);
            $("#albumImageFileName").val($("#albumImageFileName").val() + originalFileName + ", ");
            if (fileCount == files.length) {
                $("#submit").prop("disabled", false);
                currentLoaderRef.hide();
                currentTickerRef.addClass("opacity0");
                //$("progress").hide();
                $("#FileGuid").val(fileGuids.join('|'));
                $("#FileName").val(fileNames.join('|'));
            }
            break;
        case "largeFile":
            if (fileCount == files.length) {
                $("#submit").prop("disabled", false);
                currentLoaderRef.hide();
            }
            updateUploadedFilesUl(originalFileName, response.message, false);
            break;
        case "wrongFileType":
            if (fileCount == files.length) {
                $("#submit").prop("disabled", false);
                currentLoaderRef.hide();
            }
            updateUploadedFilesUl(originalFileName, response.message, false);
            break;
        case "exception":
            failedFiles++;
            if (fileCount == files.length) {
                $("#submit").prop("disabled", false);
                currentLoaderRef.hide();
                //if (failedFiles == 0)
                //    currentTickerRef.addClass("opacity0");
            }
            updateUploadedFilesUl(originalFileName, response.message, false);
            break;
    }
}

function clearFileUploadFields() {

    $("#albumImageFileName").val('');
    $("#uploadedFilesUL").html('');

    $("#FileGuid").val('');
    $("#FileName").val('');

    fileCount = 0;
    uploadedFiles = 0;
    failedFiles = 0;

    fileGuids = [];
    fileNames = [];
}

function updateUploadedFilesUl(originalFileName, message, isFileUploaded) {
    if (isFileUploaded) {
        $("#uploadedFilesUL").append("<li class='success'>" + originalFileName + "</li>")
    }
    else {
        $("#uploadedFilesUL").append("<li class='failure'>" + originalFileName + " <b>upload failed, error: " + message + "</b></li>")
    }
}

//Request error event
function uploadFailed(event) {
    hideAllLoadersAndCheckMarks();
    $("#submit").prop("disabled", false);
    $("#message").html('A problem occured while uploading the image.');
    //$("progress").hide();
}

//Request cancel upload event
function uploadCanceled(event) {
}

function hideAllLoadersAndCheckMarks() {
    $('.loader').hide();
    $('.checkmark-cover').removeClass("opacity0");
}


  
6
  • 1
    apparently, event.originalTarget is undefined Commented Jan 17 at 8:20
  • 1
    (Can you explain why you are still bothering with XMLHttpRequest in the first place, when jQuery is in use already? jQuery has an AJAX implementation that is less cumbersome, than dealing with XMLHttpRequest yourself ...)
    – CBroe
    Commented Jan 17 at 8:23
  • 2
    event.originalTarget is a non-standard event property available in Firefox only - does sometime it doesnt work on chrome mean it never works on chrome because it's a firefox only property? Commented Jan 17 at 8:26
  • @CBroe, This is an old website and i have to fix the issue as that developer has left company long back and i am not a JS guy and with KnockOutJS it even harder as we dont have anyone to work on KnockOutJS
    – Learning
    Commented Jan 17 at 9:25
  • @JaromandaX, You may be 100% correct as i was testing it on FF and issue was report by user who where user Chrome, I wonder why this issue was reported now and not for last 5-6 years. May be developer who coded this didnt knew and even not me till this point. Great Pick. I would appreciate if you can tell me what should i replace it with to support both FF & Chrome..
    – Learning
    Commented Jan 17 at 9:30

1 Answer 1

0

Issues was resolved by replacing the event.originalTarget.response with event.target.response as event.originalTarget is supported only on FireFox browser.

//only works in FF event.originalTarget.response
//var response = JSON.parse(event.originalTarget.response);
 var response = JSON.parse(event.target.response);

Credit to user @Jaromanda who pointed it out in comments.

Not the answer you're looking for? Browse other questions tagged or ask your own question.