+ Start a Discussion
steeeeveeeeeesteeeeveeeeee 

Passing a list from apex controller to javascript via remoting

So I'm using Javascript remoting to get a list that I query in the controller.  In order to return the list I use JSON.serialize to stringify the list and then in jQuery I use the parseJSON function which returns me an error. 

 

Anyone have any insight on the correct way to accomplish this?  Should I be using JSONGenerator instead?

Best Answer chosen by Admin (Salesforce Developers) 
Avidev9Avidev9

Steve, I guess you can liverage the platform feature.

The platform automatically handles it and does it pretty well!

 

 

Try this

 @RemoteAction
   public static String getAssetExpand(String assetID) {
      return aList = [SELECT ID, Name from Asset WHERE Parent_Asset__c = : assetID];
      
  }

 
Platform actually converts the list from apex to js List and presents the data to remoting method.

In your case it is converted from List to Js Array

 Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.accconhierarchy.getAssetExpand}',rowId,insertDiv);
 function insertDiv(result, event){
console.log(result);
}


 

All Answers

ryanjuptonryanjupton

JSON.serialize should work in general. Can you post your code?

steeeeveeeeeesteeeeveeeeee

Thanks for the reply

 

In the controller I have:

       @RemoteAction
       public static String getAssetExpand(String assetID)
       {

           List<Asset> aList = [SELECT ID, Name from Asset WHERE Parent_Asset__c = :assetID];
           if(aList.size() >0)
           {
               return JSON.serialize(aList);
           }
           else
               return null;
       }

 

And in the JS remoting call

 

                Visualforce.remoting.Manager.invokeAction(
                '{!$RemoteAction.accconhierarchy.getAssetExpand}',
                rowId,
                insertDiv);

 

        function insertDiv(result, event)
        {
                        var v = j$.parseJSON(result)});
 

This is what I see in Firebug:

SyntaxError: JSON.parse: expected property name or '}'
Which is apparently because the JSON is malformed.  Any ideas?
Avidev9Avidev9

Steve, I guess you can liverage the platform feature.

The platform automatically handles it and does it pretty well!

 

 

Try this

 @RemoteAction
   public static String getAssetExpand(String assetID) {
      return aList = [SELECT ID, Name from Asset WHERE Parent_Asset__c = : assetID];
      
  }

 
Platform actually converts the list from apex to js List and presents the data to remoting method.

In your case it is converted from List to Js Array

 Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.accconhierarchy.getAssetExpand}',rowId,insertDiv);
 function insertDiv(result, event){
console.log(result);
}


 

This was selected as the best answer