• Blogs (9)
    • 📱 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • jQuery: JSON and PHP:json_encode example

    Blogs20112011-10-03


    jQuery JSON and PHP json_encode example

    I have a table to list some real data, which are on-time notes about project processing:

    <table><thead>
     <tr>
      <th>No.</th>
      <th>Who Did</th>
      <th>When Did</th>
      <th>Notes</th>
      <th>...</th>
     </tr>
    </thead>
    <tbody>
    ...
    <td><textarea name="notes" id="<?=$id;?>" class="notes"
     readonly="readonly"
     onDblClick="$(this).removeAttr('readonly').css('border-width','2px');"
     onChange="$(this).notes('<?=$id;?>')"><?=$row['notes'];?></textarea>
     </td>
    </tbody>
    </table>

    The notes textarea is editable. I am going to use PHP’s json_encode() and jQuery’s json to implement a loop of AJAX-style edit and refresh. The steps:

    1. Double click textarea ‘notes’, to edit it.
    2. When finished, mouse leaves (e.g. click ‘tab’ to escape the textarea box), the notes is kept in MySQL table.
    3. After the storing, select table to get the latest record, and return in a JSON-style associate array.
    4. jQuery receives the JSON array, to use it to refresh this edited row.
    5. That means the columns: Who, When and Notes all get refresh automatically.

    For the ‘notes’ textarea:

    1. If the notes changes, do the refresh; if not change, then no refresh: ’onchange’ event.
    2. the notes arribute include readonly, it is neccessary, coz only double click to enable editing.

    This is the typical case using jQuery’s JSON. The following is the jQuery function to implement above steps:

    jQuery.fn.notes = function(id) {
      var notes = $('#'+id).val();
      var tr = $(this).closest('tr');
      $.ajax({
        type: 'post',
        url: url,
        data: 'id='+id+'&notes='+notes,
        dataType: 'json',
        success: function(data) {
          $(tr).find('td:eq(1)').text(data.username);
          $(tr).find('td:eq(2)').text(data.created);
          $('#'+id).val(data.notes);
        }
      });
      return false;
    }

    The jQuery.notes() function sends a http request (POST) to PHP, PHP operates the Database, and return the results. The following is the PHP’s reaction:

    if(isset($_POST['notes']) || isset($_POST['id'])) {
     $sql = "update table set notes='".
        mysql_real_escape_string(trim($_POST['notes']))."'
       WHERE active='Y'  AND id=".$_POST['id'];
     mysql_query($sql) or die (mysql_error());
     $res = mysql_query("SELECT * FROM test WHERE id=".$id);
     $data = mysql_fetch_assoc($res);
     mysql_free_result($res);
     echo json_encode($data);
    }

    Here I use PHP’s json_encode function. The json_encode returns an associate array instead of plain data to Javascript (here is jQuery AJAX). Its return like this:

    {"id":"2","uid":"88","username":"test",
      "created":"2011-09-30 10:31:02","result":"Done",
      "notes":"this is a 'test'.nnew adding.","active":"Y"}

    So when success, PHP sends JSON array data to jQuery, jQuery use the data to refresh the editing row:

    success: function(data) {
     $(tr).find('td:eq(1)').text(data.username);
     $(tr).find('td:eq(2)').text(data.created);
     $('#'+id).val(data.notes);
    }

    That’s a whole processing of a Javascript:json and PHP:json_encode. It is largely used in modern web apps.