Liam Jack Liam Jack - 4 months ago 34
Ajax Question

Jquery error : too much recursion

I'm trying to create a file upload system implementing client side encryption using CryptoJS.

The problem I'm having is that execution of the script is stopped by the following error in Firebug's console :

too much recursion


I have spent half of the day trying to resolve the problem, removing the
var jqxhr = $.ajax
part removes the error but removes posting functionality from my script. I have tried removing all the encryption lines, separating into different functions, but nothing seems to do it. Any jQuery pros know what's going wrong ?

Here's the code :

$("#successmsg").hide();
$("#errormsg").hide();

function randomString(n)
{
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

for(var i=0; i < n; i++)
{
text += possible.charAt(Math.floor(Math.random() * possible.length));
}

return text;
}


$("#upload").submit(function(event) {
event.preventDefault();

input = document.getElementById('file');

if(!input.files[0]) {
$("#errormsg").html("No file selected.");
$("#successmsg").hide();
$("#errormsg").show();
}

fr = new FileReader();

fr.onload = function() {
var fname = input.files[0].name;
var fkey = CryptoJS.SHA256(randomString(128));
var skey = CryptoJS.SHA256(fkey);

var fdata = CryptoJS.AES.encrypt(fr.result, "TestPassword");

var jqxhr = $.ajax({
url: "/api/files/upload",
type: "POST",
data: {
'name': fname,
'data': fdata,
'key': skey
},
cache: false,
dataType: 'json',
processData: false
});
}

fr.readAsText(input.files[0]);
});


Here is a JSFiddle : http://jsfiddle.net/wob66Lc0/

Answer

The issue is that CryptoJS functions return objects not strings, so you have to stringify it before you attempt to send it.

    var jqxhr = $.ajax({
        url: "/api/files/upload",
        type: "POST",
        data: {
            'name': fname,
            'data': fdata.toString(),
            'key': skey.toString()
        }
    });

http://jsfiddle.net/wob66Lc0/1/

Also encryption works on bytes not text so you should read the file as a binary string instead of text

fr.readAsBinaryString(input.files[0]); 
Comments