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. $.ajax({
  3. type: <GET/POST>,
  4. contentType: "application/json; charset=utf-8",
  5. url: <TARGET URL>\<SERVER SIDE METHOF NAME>,
  6. data: JSON.stringify({ <PARAMETER TO SEND>: <VALUE> }),
  7. async: <true/false>,
  8. dataType: "json",
  9. success: function (data) {<TO DO>
  10. returnflag = true;
  11. },
  12. error: function (result) {
  13. returnflag = null;
  14. }
  15. });
  16. }
Server side:
  1. [WebMethod]
  2. public static string <SERVER SIDE METHOF NAME> (<PARAMETER>)
  3. {
  4. ….
  5. Return XYZ;;
  6. }
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. regNum = document.getElementById('txtRegnum').value;
  5. if (regNum != '') {
  6. $.ajax({
  7. type: "POST",
  8. contentType: "application/json; charset=utf-8",
  9. url: "default.aspx/getStudentName",
  10. data: JSON.stringify({ RegNum: regNum }),
  11. async: false,
  12. dataType: "json",
  13. success: function (data) {
  14. if (data.d == '') {
  15. document.getElementById('lblStudentName').innerHTML = '';
  16. }
  17. document.getElementById('lblStudentName').innerHTML = data.d;
  18. returnflag = true;
  19. },
  20. error: function (result) {
  21. returnflag = null;
  22. }
  23. });
  24. }
  25. }
  1. [WebMethod]
  2. public static string getStudentName (string RegNum )
  3. {
  4. ….
  5. Return XYZ;;
  6. }