+ Start a Discussion
Sai Ram ASai Ram A 

Communication Between JSON String and JavaScript in Visualforce page


I have a Simple controller returns list of Accounts  in JSON String format, I have structured well to map with Script in vf page. But i m unable map in Script in visualforce page. Please suggest

Please click here to see the screenshot of requirement https://developer.salesforce.com/forums/ForumsMain?id=906F0000000B3tpIAC
<apex:page controller="JSONGeneratorController"  docType="HTML-5.0" >
    <apex:stylesheet value="{!URLFOR($Resource.JQueryDataTable, '/css/jquery.dataTables.css')}"/> 
    <!-- jQuery library -->
    <apex:includeScript value="{!URLFOR($Resource.JQueryDataTable, '/jquery.dataTables.min.js')}"/>
    <apex:includeScript value="{!URLFOR($Resource.JQueryDataTable, '/jquery-1.11.1.min.js')}"/> 
        /* Formatting function for row details - modify as you need */
        function format ( d ) {
            // `d` is the original data object for the row
            return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
                    '<td>Account Type:</td>'+
                    '<td>Extra info:</td>'+
                    '<td>And any further details here (images etc)...</td>'+
        function buildAccountsTable(){  
        var j$ = jQuery.noConflict();
          var allAccounts = {!jsonDataAllAccounts};  // This return the Accounts in JSON Format
          $(document).ready(function() {
            var table = $('#example').DataTable( {
                "ajax": allAccounts ,                             //Passing list Account variable to build Rows
                "columns": [
                        "className":      'details-control',
                        "orderable":      false,
                        "data":           null,
                        "defaultContent": ''
                    { "data": "name" },
                    { "data": "industry" },
                    { "data": "owner" },
                    { "data": "rating" }
                    //{ "data": "acctType" },
                    //{ "data": "revenue" },
                    { "data": "numberOfEmployees" }
                "order": [[1, 'asc']]
            } );
          // Add event listener for opening and closing details
            $('#example tbody').on('click', 'td.details-control', function () {
            var tr = $(this).closest('tr');
            var row = table.row( tr );
            if ( row.child.isShown() ) {
                // This row is already open - close it
            else {
                // Open this row
                row.child( format(row.data()) ).show();
            } );
            } );
<apex:form >

   <apex:outputPanel id="allAccountTables">  
      <table id="allAccounts" class="display" cellspacing="0" style="width:90%; padding-bottom:10px; border-style:solid;">  
                     <th style="width: 25%;">Name</th>  
                     <th style="width: 13%;">Rating</th>  
    <apex:pageBlock >

Apex Controller Class 
public with sharing class JSONGeneratorController {

    public String jsonString { get; set; }

    public List<Account> accontList {get; set;}

    //define shape of Json Response salesforce
    public JSONGeneratorController (){
        jsonString = Json.SerializePretty(getAccountList());
    //List of Accounts & its accociated Contacts should be displayed on click on + image
    public static List<Account> getAccountList(){
        return ([SELECT Id, Name, OwnerId, Owner.Name, Ownership, Industry, AnnualRevenue,  Type, Rating, NumberOfEmployees, (SELECT FirstName, LastName FROM Contacts WHERE AccountId != null) FROM Account ORDER BY Name ASC LIMIT 10]);
        //return ([SELECT Id, Name,Phone,  OwnerId, Owner.Name, Ownership, Industry, AnnualRevenue,  Type, Rating, NumberOfEmployees FROM Account ORDER BY Name ASC LIMIT 10]);
    //Wrapper class
    public class DataTableRow {  
      public String name { get; set; }  
      public String industry { get; set; }  
      public String owner { get; set; }  
      public String rating { get; set; }  
      public String ratingFlag { get; set; }  
      public Decimal revenue { get; set; }  
      public String revenueFlag { get; set; }  
      public String acctType { get; set; }  
      public Integer numberOfEmployees { get; set; }  
      public Id recordId { get; set; }  
      public DataTableRow(Account acct){  
           this.name = acct.Name;  
           this.industry = acct.Industry;  
           this.owner = acct.Owner.Name;  
           this.rating = acct.Rating;  
           this.revenue = acct.AnnualRevenue;  
           this.acctType = acct.Type;  
           this.numberOfEmployees = acct.NumberOfEmployees;  
           this.recordId = acct.Id;  
    //JSON String
    public String jsonDataAllAccounts {  
      get {  
           List<DataTableRow> dataRows = new List<DataTableRow>();  
           if(jsonDataAllAccounts == null){  
                for(Account acct : [SELECT Id, Name, OwnerId, Owner.Name, Ownership, Industry, AnnualRevenue,  Type, Rating, NumberOfEmployees FROM Account ORDER BY Name ASC LIMIT 10]){  
                     dataRows.add(new DataTableRow(acct));  
           jsonDataAllAccounts = JSON.serializepretty(dataRows);  
           system.debug('get set variable'+jsonDataAllAccounts);
           return jsonDataAllAccounts;   
      private set;  

NagaNaga (Salesforce Developers) 
Hi Sairam,

Below is the sample code of how JSON and Javascript communicate with each other.

User-added image

Please see the link below for more assistance


Best Regards
Naga Kiran
Pramodh KumarPramodh Kumar
Hi Sairam

I am using same Datatable for the client side pagination. however if i pass the jsonstring to the javascript i am getting the invalid json string,

I am getting output [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object] in the console. Please help me if have any solution.