5.7 Lightweight data-interchange format - JSON

  1. Motivations
    • I'd like to receive data, not HTML content, from the server. For example, just data, not table code, for the search results in TRUQA. Any formal data format with AJAX?

  2. Let's study JSON.
    • Read all in JSON - Introduction.
      • What is JSON data in JavaScript?
      • For what do you use JSON?
      • Can a JSON file be a target URL for AJAX?
      • Is the JSON format syntactically identical to the code for creating JS objects?
      • What function is used to parse a JSON string into a JavaScript object?
      • Trial 1: Let's convert the object for 'ListQuestions' to a string, and the string to an object.


    • Read all in JSON Syntax.
      • Can you use single quotes?    No.
      • List the 6 types of JSON values
      • What is the extension of JSON files?
      • What is the MIME type for JSON text?
    • Read all in JSON How To.
      • In the examples, do you think employees[0]['firstName'] + " " + employees[0].lastName; will work? This idea can be used in many interesting ways.
    • Read all in JSON Http Request.
      • Read the first example carefully.
      • What is XMLHttpRequest?
      • What kind of bracket is used for JSON arrays?
      • What kind of data is stored in 'myTutorials.txt'?
      • Can you move the AJAX routine into an external JavaScript file and include the file?
      • Trial 2: Let's get the list of questions from TRUQA, and display it in a table.


      • Trial 2.5: Can you add table headers with property names in the above Trial 2?
      • Trial 2.6: Can you attach delete buttons in each row in the table in the above Trial 2? How to obtain the Id value when the delete button is clicked? It can be used when the DeleteQuestion command is submitted.


      • Do you know how to delete a table row when a delete button in Trial 2.6 is clicked?
        • Send the DeleteQuestion command with the id stored in the delete button. How?
          $(this).attr("data-q-id")
        • Delete the row where the button is clicked. How?
          document.getElementById("myTable").deleteRow(this.parentNode.parentNode.rowIndex); or
          $(this).parent().parent().remove()
      • Trial 2.7: Let's search questions from TRUQA, and display it in a table.


      • Trial 3: Let's write a JSON file.


      • Can you add table headers in the above Trial 3?
    • How to convert a JSON object to a string?
    • How to convert a JSON string to PHP variables?
      • json_encode(): E.g., an array to a JSON string
      • json_decode(): E.g., a JSON encoded string to an ...

  3. How to use JSON for TRUQA
    • How to send the 'SearchQuestions' result to the client from the server?
      // Model
      
      function search_questions($search_term) 
      {
          global $conn;
          
          $sql = "??? Id, Question, Date from Questions ??? Question like '%" . $search_term . "%'";
          $result = ???($conn, $sql);
      
          $str = '[';
          $first = true;
          while($row = ???($result)) {
              if ($first) $first = false;
              else $str .= ',';
              // $str .= '{"Question":"' . $row['Question'] . '", "Date":"' . $row['Date'] . '"}';  // {"Question" => "...", "Date" => "..."}
              $str .= ???($row);  // json_???
          }
          $str .= ']';
          return $str;
      }
      
      // Controller
      
      echo search_questions($t);
      
      /* or
      * It is more desirable.
      */
      
      // Model
      
      function search_questions($search_term)
      {
          global $conn;
          
          $sql = "??? Id, Question, Date from Questions ??? Question like '%" . $search_term . "%'";
          $result = ???($conn, $sql);
          
          $data = array();  // []
          $i = 0;
          while($row = ???($result))
              $data[$i++] = $row;  // $row: an associative array
          return $data;
      }
      
      // Controller
      
      echo ???(search_questions($t));  // Convert the array to a JSON string and send
                                       // In general, you should not include MainPage or StartPage
      
    • How to use the data sent from the server?
      $('#button-search-questions').click(function() {
          var search_terms = ...;
          $.post('controller.php',
              { ???? },
              function(result) {  // retult: '[{...}, ...]'
                  $('#result-pane').???('<h3>Searched Questions</h3>' + construct_table('List of questions', result));
          });
      });
      
      function construct_table(caption, data)  // data: '[{...}, ...]'
      {
          // Convert the JSON string to an object
          var obj = ???.???(data);  
          // table tag
          var table = '<table>';
          // table caption
          table += ??? + caption + '</caption>';
          // table headers
          table += '<tr>';
          for (var p in obj[???][0])
              table += '<th>' + ??? + '</th>';  // property names
          table += '</tr>';
          // table data
          for (var i = 0; i < obj[???].???; i++) {
              table += '<tr>';
              for (var p in obj[???])
                  table += '<td>' + ??? + '</td>';  // property values
              ????  // add some buttons.
              table += '</tr>';
          }
          // table end tag
          table += '</table>';
      
          return table;
      }
      
    • Trial 4: Let's try to send the list of questions in the JSON form.


    • Trial 4.5: Can you add table headers in the above Trial 4?

  4. Something with which we need to be careful
    • In the case that there are double quouts in a string value
      • Trial 5: Let's try the next example. Be careful with double quotes in string values.



  5. Some review questions and learning outcomes
    • Write JSON data.
    • Use AJAX to retrieve JSON and text data.