Example 2 – user feedback powered by AJAX and the jQuery UI

In this example, we will show how we can use the jQuery UI with AJAX to call a CI AJAX controller method to collect the user feedback, and submit it without refreshing/rendering a page.

We will reuse and expand the login example from Chapter 3, Usage and Scope of Controllers, so if a user is logged in, we will log the feedback with the user ID kept in the session, while if not, we will log it as anonymous user feedback.

Remember the following things:

  • Username: reg_user,
  • Password: 111111111 (9 by 1s) for regular user login

The reused and extended resources are as follows:

  • auth.php: No change here
  • ajax_handler.php: This is the new AJAX handler controller
  • users_model.php: This is the extended user model
  • logged_in_view.php: This is the extended view for regular user login

We expand the code to include the new Ajax_handler to keep the jQuery UI dialog submission of the browsing user feedback, as well as get the user logged message via the AJAX asynchronous interface. Note that we check in Ajax_handler to see whether the request is AJAX or not. And if it's not, we issue the following URL in the browser:

http://photographersnav.com/ci_utils/index.php/ajax_handler.

We will get a notification in the browser that this is a bad request.

The users_model resource is expanded to provide a few more services, which are as follows:

  • get_logged_in_user(): This function is used to return the logged in user record if logged in or NULL otherwise. get_user_rec ( $uid ) to get a specific user record based on his/her ID.
  • keep_user_feedback ($feedback): This function is used to keep the user feedback in the database with its user ID, if logged in.
  • get_user_feedbacks ($uid): This function get all the user feedback messages save till now in the database as an array of the database objects. Each feedback database row returned have the feedback message and its timestamp formatted as HTML and returned via the JSON format back to the AJAX caller to be shown to the end user via the jQuery selector based HTML rendering (for example, $(selector).html (The_html_item_returned_from_server)).

The logged_in_view resource is expanded to provide the user with the new services as follows:

  • Add a new feedback button, which when clicked pops-up a jQuery UI dialog for this purpose
  • Show the feedback log button, which when clicked shows a scrollable list of the user feedback

Now let us review the source code itself.

The ajax_handler.php controller file

The controller PHP file is located at application/controllers/ajax_handler.php. The code and inline explanations are as follows:

<?php if (!defined('BASEPATH'))exit('No direct script access allowed'),
class Ajax_handler extends CI_Controller {
  function __construct()
  {parent::__construct();
    /* Standard libraries, database & helper URL loaded via theauto load
    */
    if (!$this->input->is_ajax_request())
    {exit( "Bad Request ignored! - Your info has been logged forfurther investigation of attacking the site!");
    }
  /* ------ Our Users Model ---------- */
  $this->load->model ( 'users_model' );
}

functionsave_user_feedback () {
  // Get the feedback content
  $feedback = $this->input->post('feedback'),
  // Get if the user is logged in keep the user id
  $this->users_model->keep_user_feedback($feedback);
  }
functionget_user_feedback_log () {
  $user = $this->users_model->get_logged_in_user ();
  if ( $user ) $uid = $user->id;
  $user_feedback_rows = $this->users_model->get_user_feedbacks( $uid );
  $html = '';
  foreach ($user_feedback_rows as $row )
  $html.= $row->timestamp.' -  <B>'.$row->feedback.'</B><BR/>';
  $result = array ('result' => $html);
  echojson_encode ($result);
  return;
  }
} // End Ajax_handler

The users_model.php model file

The model PHP file is located at application/models/users_model.php. The code and inline explanations are as follows:

<?php if (!defined('BASEPATH'))
exit('No direct script access allowed'),
class Users_model extends CI_Model {
  function __construct()
  {parent::__construct();
  }
  functioncheck_login ($user, $pass)
  {
    /* No change here
    */ 
    }
  functionget_logged_in_user (  )
  {
    // Will check if there's a login user session and if so will// fetch its record
    $ci = &get_instance();
    
    //get the login in user ID, if any
    $uid = $this->session->userdata('user_id'),
    if (! $uid ) return NULL;
    $sql = "SELECT *
    FROMusers
    WHERE id = '$uid' ";
    
    $q = $ci->db->query($sql);
    if ($q->num_rows())
    {foreach ($q->result() as $row )
      return $row;
      }
    return NULL;
    }
    Function get_user_rec ( $uid ){
      // Will check if there's a login user session and if so will// fetch its record
      $ci = &get_instance();
      // get the login in user ID, if any
      if (! $uid ) return NULL;
      $sql = "SELECT *FROM users WHERE id = '$uid' ";
      $q = $ci->db->query($sql);
      if($q->num_rows())
      {foreach ($q->result() as $row ) return $row;
        }
      return NULL;
      }
    Function keep_user_feedback ($feedback) {
      $ci = &get_instance();
      $uid_rec = $this->get_logged_in_user ();
      $uid = $uid_rec ? $uid_rec->id: 0;
      /* id email uid feedback timestamp
      */
      $table = 'user_feedback';
      $data = array ( 'feedback'  =>urldecode ($feedback),'uid'=>  $uid);
      $ci->db->insert($table, $data);
      }
      Function  get_user_feedbacks ( $uid ) {
        $ci = &get_instance();
        if (! $uid ) return NULL;
        $feedbacks = array();
        $table = 'user_feedback';
        $sql = "SELECT * FROM  $tableWHERE  uid = '$uid'
        ORDER BY timestamp DESC";
        $q = $ci->db->query($sql);
        if ( $q->num_rows() ) {
          foreach ($q->result() as $row)
          $feedbacks[] = $row;
          }
        return $feedbacks;
        }
      } // End Users_model

The logged_in_view.php view file

The PHP view file is located at application/views/logged_in_view.php. This file was extended with several more services, as described in the previous examples. The code and inline explanations are as follows:

<!DOCTYPE html">
<meta http-equiv="Content-type" content="text/html;charset=utf-8" />
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js" type='text/javascript'></script>
<scriptsrc="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js">
</script>
<link rel="stylesheet" type="text/css" href="<?=base_url(); ?>/css/my_style.css" media="screen" />
<script type='text/javascript'>
// The AJAX handler controller method URLs
varsave_user_feedback_submitter = '<?=site_url()?>'+'index.php/ajax_handler/save_user_feedback';
varget_user_feedbacks = '<?=site_url()?>' +'index.php/ajax_handler/get_user_feedback_log';
functionajax_save_user_feedback (feedback) {
  $.ajax({
    type : "POST",
    url : save_user_feedback_submitter,
    data : {feedback: feedback},
    dataType: "json",
    success: function(data) {
      // When AJAX return back alert // ('Your feedback Updated - Thanks!'),
      }
    });
  }

functionajax_get_user_feedback_log() {
  $.ajax({
    type: "POST",
    url: get_user_feedbacks,
    dataType: "json",
    success: function(data) {
      $('#feedback_log_view').show();
      $('#feedback_log_view').html(data.result);
      }
    });
  }
$(document).ready(function() {
  // Set up the jQuery UI feedback dialog
  $("#ideas-form").dialog({
    autoOpen: false,
    height: 270,
    width: 700,
    modal: true,
    resizable: false,
    effect: 'drop',
    direction: "up",
    show: "slide",
    buttons: {
      "Send Us Your Feedback": function() {
        varuser_feedback = $('#user_feedback').val();
        ajax_save_user_feedback(user_feedback);
        // clean feedback entry for next one
        $('#user_feedback').val(''),
        // Show user all its feedback so far
        ajax_get_user_feedback_log();
        $(this).dialog("close");
        },
      "Cancel": function() {
        $(this).dialog("close");
        }
      }
    });
  
  // When user clicks on for a popup feedback window
  $('#user_ideas').button().click(function() {
    $("#ideas-form").dialog("open");
    });
  
  $('#feedback_log').button().click(function() {
    ajax_get_user_feedback_log();
    });
  });// Document ready section
</script >
</head>
<body>
<H1>Welcome <?=$user_name; ?>! </H1>
<H1>You are logged in! </H1>
<HR></HR>
  <H3>Your User ID is: <?=$uid; ?></H3>
  <H3>Your System Role is: <?=$role; ?></H3>
  <H3>Your Menu options: <?=$menu; ?></H3>
<DIV>
  <button id='user_ideas' style="cursor: pointer; position: relative; top:0px" title='Share your feedback/ideas'> Add A New Feedback </button><BR/>
  <button id="feedback_log" style= "cursor: pointer; position: relative; top:0px" title="Your feedback log"> See Your Feedback Log </button>
</DIV>
  <div id='feedback_log_view' style= "display: none; width: 800 px; border-style: solid;border-color: black; overflow-x: auto; height: 200 px; overflow-y: auto;">
</DIV>
<H2><?php echo anchor ('index.php/auth/logout', 'Logout')?></H2>

  <div id= "ideas-form", title= "Your Feedback To Improve">
<form>
<fieldset>
<span id= "user_name" class= "text ui-widget-content ui-corner-all"> Thanks <? = $user_name; ?>, Please share your feedback with us</span>
<textarea name= "idea_desc", id = "user_feedback", rows = "10" cols = "83", placeholder = 'Your ideas'></textarea>
</fieldset>
</form>
</div>
</body>
</html>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.73.175