Category Archives: JavaScript

JSON

Biswajeet   May 3, 2014   No Comments on JSON

JSON (JavaScript Object Notation) is a lightweight and text-based data-interchange format. Supports with UTF-8 and date-time information in ISO8601 format. It uses string value pairs for storing data.

Basically it is used to transmit data between a browser and a server. When exchanging data between a browser and a server, the data can only be text. JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.

Example:

{
   "firstName":"Biswajeet",
   "lastName":"Samal",
   "isAlive":true,
   "age":28,
   "address":{
      "streetAddress":"25 2nd Street",
      "city":"New York",
      "state":"NY",
      "postalCode":"10021-3100"
   },
   "phoneNumbers":[
      {
         "type":"home",
         "number":"212 888-1234"
      },
      {
         "type":"office",
         "number":"646 989-4567"
      },
      {
         "type":"mobile",
         "number":"123 456-7890"
      }
   ],
   "children":[

   ],
   "spouse":null
}

JSON supports following data types:

  • string
  • {"name":"Biswajeet Samal"}
  • number
  • {"age":28}
  • object
  • {
    "employee":{ "name":"Biswajeet Samal", "age":28, "city":"London" }
    }
  • array
  • {
    "employees":[ "Biswajeet", "Abhijeet", "Satyajeet" ]
    }
  • boolean
  • {"isAlive":true}
  • null
  • {"spouse":null}

Passing Variables from Apex to JavaScript

Sometimes we need to pass variables from apex to javascript. Here is an example to pass variables from apex to javascript. In below example I’m invoking one apex method using action function. In the apex method I’m defining the apex variable value. On complete of action function I’m invoking one javascript method and using the apex variable in the javascript method.

Visualforce Page:

<apex:page controller="SampleController">  
    <apex:form>
        <apex:outputPanel id="jspanel"> 
            <script>  
            function onCompleteMethod() {
                alert('{!message}')
            }
            </script>
        </apex:outputPanel>
        <apex:actionFunction name="afHelloWorld" action="{!HelloWorld}" rerender="jspanel"/>
        <apex:commandButton onclick="afHelloWorld();" oncomplete="onCompleteMethod()" value="Click me"/>
    </apex:form>
</apex:page>

Apex Class:

public class SampleController {
    
    public String message {get;set;}
    
    public pageReference HelloWorld() {
        message = 'Hello World!!';
        return null;
    }   
}