[SalesForce] How to return the Array or List from RemoteAction Method to Javascript

I have a Javascript code which is used to call the method of a Controller using the @RemoteAction.

This is my Javascript coding

var arr = new Array('123', '234');
arr.splice(0, 1);
arr.splice(0, 1);
processByteChunkArray(arr);
// Here i tried this to make sure the empty array is passing or not

function processByteChunkArray(getResult) {
    FileUploadController.attachBlob(getResult, function(result, event) {
        //Proceed if there were no errors with the remoting call
        if (event.status == true) {
            alert(result);//This alert is coming
            getResult = JSON.parse(result);
            alert(getResult);//This alert is NOT coming
            processByteChunkArray(getResult);
        } else {
            checkForUploads();
        }
    });
}

This is Controller Coding

global static List<Attachment> attachList = new List<Attachment>();
@RemoteAction
global static List<Attachment> attachBlob(List<Attachment> getResult) {
    Attachment att = new Attachment(
        ParentId = parentId,
        Body = EncodingUtil.Base64Decode(base64BlobValue),
        Name = fileName,
        ContentType = contentType
    );
    if (getResult.size() > 0) {
        for (Attachment atm: getResult) {
            try {
                atm.Body = EncodingUtil.Base64Decode(EncodingUtil.Base64Encode(atm.Body) + base64BlobValue);
                attachList.add(atm);
            } catch (Exception e) {
                System.debug('This is in IF CATCH Condition===>' + e.getMessage());
            }
        }
        return JSON.serialize(attachList);
    } else {
        try {
            attachList.add(att);
        } catch (Exception e) {
            System.debug('This is in ELSE CATCH Condition' + e.getMessage());
        }
        return JSON.serialize(attachList);
    }
}

And now my problem is, the List that i am returning on the Controller Method is not coming to Javascript. I tried the Same coding returning the STRING and it is working perfectly. Why not List<Attachment>.

I tried returning both List<Attachment> and Attachment[] but with no result in the Javascript.
Is there any difference between List and Array?

UPDATE:

I updated the coding according to the JSON Serialize and parse. The Serialize is working but the parse is not working. Is there any way to parse the String to an array again and i need to store that array in the getResult variable

Please help…

Best Answer

I suggest return the JSON string from method like.. first serialize the list and return

global static String attachBlob(List<Attachment> getResult) {

   // your code 

   return JSON.serialize(attachList);
}

I am not sure but I guess you may need to parse the javascript variable ie. result

like this JSON.parse(result). this will give you the array

Related Topic