Real Time Example of JavaScript Object Notation (JSON)

Introduction

 
JavaScript Object Notation is an open standard format that uses human-readable text to transmit data objects consisting of attribute-value pairs. It is used primarily to transmit data between a server and web application, as an alternative to XML.
 
Uses
  1. JSON is a lightweight data-interchange format.
  2. JSON is language independent
  3. JSON is "self-describing" and easy to understand.
Syntax
 
In client-side.
  1. function <FUNCTION NAME> (<PARAMETER OPTIONAL>) {  
  2.      
  3.         $.ajax({  
  4.   
  5.             type: <GET/POST>,  
  6.             contentType: "application/json; charset=utf-8",  
  7.   
  8.             url: <TARGET URL>\<SERVER SIDE METHOF NAME>,  
  9.   
  10.             data: JSON.stringify({ <PARAMETER TO SEND>: <VALUE> }),  
  11.             async: <true/false>,  
  12.             dataType: "json",  
  13.   
  14.             success: function (data) {<TO DO>  
  15.               returnflag = true;  
  16.             },  
  17.   
  18.             error: function (result) {  
  19.                 returnflag = null;  
  20.             }  
  21.         });  
  22.      
  23. }  
Server side:
  1. [WebMethod]  
  2. public static string <SERVER SIDE METHOF NAME> (<PARAMETER>)  
  3. {  
  4.    ….  
  5.    …  
  6.   
  7.    Return XYZ;;  
  8. }  
Example:
 
The scenario is we need to get the student name based on the register number.
  1. <asp:TextBox Width="80px" MaxLength="32" ID="txtRegnum" runat="server"onblur="getName();" ></asp:TextBox>  
  2. <asp:Label ID="lblStudentName" runat="server" ></asp:Label>  
  1. function getName() {      
  2.     var regNum = '';  
  3.     var returnflag;  
  4.   
  5.     regNum = document.getElementById('txtRegnum').value;  
  6.   
  7.     if (regNum != '') {  
  8.         $.ajax({  
  9.   
  10.             type: "POST",  
  11.             contentType: "application/json; charset=utf-8",  
  12.             url: "default.aspx/getStudentName",  
  13.             data: JSON.stringify({ RegNum: regNum }),  
  14.             async: false,  
  15.             dataType: "json",  
  16.   
  17.             success: function (data) {  
  18.   
  19.                 if (data.d == '') {  
  20.                     document.getElementById('lblStudentName').innerHTML = '';  
  21.                 }  
  22.                 document.getElementById('lblStudentName').innerHTML = data.d;  
  23.                 returnflag = true;  
  24.             },  
  25.   
  26.             error: function (result) {  
  27.                 returnflag = null;  
  28.             }  
  29.         });  
  30.     }     
  31. }  
  1. [WebMethod]  
  2. public static string getStudentName (string RegNum )  
  3. {  
  4.    ….  
  5.    …  
  6.   
  7.    Return XYZ;;  
  8. }