Category: JQuery


In all Entertainment sites, Star rating is a common phenomena. We need to use star rating for rating different resources like videos, articles, thesis, posts even sometimes persons. JQuery has an excellent Star Rating plugin, which I recently use with PHP CodeIgniter. This is very simple to integrate with controller and show high quality rating options.

Jquery Call:


$(function() {
       $('.auto-submit-star').rating({
            required: true,
            callback: function(value, link) {

            $.ajax({
                     type: "post",
                     url: site_url + "user/view/star",
                     dataType: "json",
                     data: "&video=" + $('#video_url').val() + "&rate_val=" + value,

              success: function(e) {
                   $.jGrowl(e.code + "<br>" + e.msg);
               }
         });
     }
});

Controller Method:

public function star()
    {
        $rate = $this->input->post("rate_val", true);
        $video_url = $this->input->post("video", true);
        $this->load->model("Model Name");
        $video_id = $this->model_name->get_video_id($video_url);
        unset($this->layout); //Block template Layout
        if (get_user_id())   //get_user_id() return login user id
        {
            if (!$this->model_name->is_video_rated(get_user_id(), $video_id))
            {
                $data = array("video_id" => $video_id,
                    "user_id" => get_user_id(),
                    "videos_rating_value" => $rate,
                    "videos_rating_date" => "" . date("Y-m-d H:i:s") . ""
                    );
                if ($this->model_name->insert_rating($data, $video_id, $rate))
                {
                    echo json_encode(array("code" => "Success", "msg" => "Your Video Rating has been posted"));
                }
                else
                {
                    echo json_encode(array("code" => "Error", "msg" => "There was a problem rating your video"));
                }
            }
            else
            {
                echo json_encode(array("code" => "Error", "msg" => "You have already rated this video"));
            }
        }
        else
        {
            echo json_encode(array("code" => "Error", "msg" => "You have to login to rate the video"));
        }
        exit(0);
    }

Presentation View:

    if (!get_user_id()) //Check if user logged in
    {
        $radio_level = "disabled";
    }
    else
    {
        $radio_level = " ";
    }

    for($i = 1;$i <= 5;$i++)
    {
        if ($i == round($row["total_rate"]))
        {
       ?>
       <input class="auto-submit-star" type="radio" name="rating" <?php echo "$radio_level";

            ?> value="<?php echo $i;

            ?>" checked="checked"/>
	<?php
        }
        else
        {
         ?>
	<input class="auto-submit-star" type="radio" name="rating" <?php echo "$radio_level";

            ?> value="<?php echo $i;

            ?>"/>
   <?php
        }
    } //end of for
?>
    

Its a very cool 🙂 rating JQuery plugins.
For demo click

Advertisements

JQ Grid with Codeigniter

jQGrid is a free jQuery grid and table plugin. I had awesome working experience on JQGrid. Its is very simple and easy to integrate with the main library. last couple of days, I received some requests on how to integrate JQGrid with Codeigniter.

Follow the steps to integrate JQGrid with CI:

Controller:

public function browse ()
	{
		$req_param = array (

				"sort_by" => $this->input->post( "sidx", TRUE ),
				"sort_direction" => $this->input->post( "sord", TRUE ),
				"page" => $this->input->post( "page", TRUE ),
				"num_rows" => $this->input->post( "rows", TRUE ),
				"search" => $this->input->post( "_search", TRUE ),
				"search_field" => $this->input->post( "searchField", TRUE ),
				"search_operator" => $this->input->post( "searchOper", TRUE ),
				"search_str" => $this->input->post( "searchString", TRUE ),
				"search_field_1" => "msg_to",
				"search_field_2" => "msg_in_inbox",
				"user_id" => get_user_id()
		);

		$data->page = $this->input->post( "page", TRUE );
		$data->records = count ($this->model_name->get_data ($req_param,"all")->result_array());
		$data->total = ceil ($data->records /10 );
		$records = $this-> model_name-> get_data ($req_param)->result_array();
		$data->rows = $records;

		echo json_encode ($data );
		exit( 0 );
	}

Models:

public function get_data($params = "" , $page = "all")
	{

		$this->db->select("data")->from( "table_name");

		if (!empty($params))
		{
			if ( (($params ["num_rows"] * $params ["page"]) >= 0 && $params ["num_rows"] > 0))
			{
				if  ($params ["search"] === TRUE)
				{
					$ops = array (

							"eq" => "=",
							"ne" => "<>",
							"lt" => "<",
							"le" => "<=",
							"gt" => ">",
							"ge" => ">="
					);

				}

				if ( !empty ($params['search_field_1']))
				{
					$this->db->where ($params['search_field_1'], $params['user_id']);
				}

				if ( !empty ($params['search_field_2']))
				{
					$this->db->where ($params['search_field_2'], "1");
				}

				$this->db->order_by( "{$params['sort_by']}", $params ["sort_direction"] );

				if ($page != "all")
				{
					$this->db->limit ($params ["num_rows"], $params ["num_rows"] *  ($params ["page"] - 1) );
				}

				$query = $this->db->get();

			}
		}
		else
		{
				$this->db->limit (5);
				$query = $this->db->get ($this->_table );

		}
		return $query;
	}

Views:

<script type="text/javascript">
$(document).ready(function(){
	jQuery("#grid_name").jqGrid({
	   	url:'<?php
		      echo site_url( "message/inbox/browse" );
		      ?>',
		datatype: "json",
		mtype : "post",
		colNames:['col 1','col 2','col 3','col 4'],
	   	colModel:[
			{name:'msg_id',index:'msg_id', width:70, align:"center",hidden:true},
	   		{name:'sender',index:'sender', width:180},
	   		{name:'msg_subject',index:'msg_subject', width:180,align:"left"},
	   		{name:'msg_timestamp', index:'msg_timestamp', width:150},
	   		{name:'act',index:'act', width:90, align:"center", sortable:false}
	   	],
	   	rownumbers: true,
	   	rowNum:10,
	   	rowList:[10,20,30],
	   	pager: jQuery('#pager2'),
	   	sortname: 'msg_timestamp',
	   	autowidth: true,
	   	height: "100%",
	    viewrecords: true,
	    loadComplete: function(){
						$("#grid_name").setLabel("id","",{'text-align':'center'});
						$("#grid_name").setLabel('role_name',"",{'text-align':'center'});
						var ids = jQuery("#grid_name").getDataIDs();
							for(var i=0;i<ids.length;i++){

								var cl = ids[i];

								be = '<span class="one_line">'
								+'<a href="javascript:;" onclick="del_message(\''+ids[i]+'\');"><span class="ui-icon ui-icon-closethick"></span></a>'
								+'</span>';
								jQuery("#grid_name").setRowData(ids[i],{act:be});
							}
					    },

	    sortorder: "desc",

	    jsonReader: { repeatitems : false, id: "0" },
	    caption:"Caption Text");?>"
	}).navGrid('#pager2',{edit:false,add:false,del:false});
});

function del_message(message_id)
{
	if(confirm("Confirm Message")){

		$.ajax({
			url : site_url+"/message/inbox/del_message",
			type : "post",
			dataType : "json",
			data : "message_id="+message_id+"",
			success : function(e){
				$("#msg").html(e.msg)
				alert($("#msg").html());
				//$.jGrowl(e.code+"<br>"+e.message);
				jQuery("#grid_name").trigger("reloadGrid");
			}
		});
	}
}

</script>

HTML BODY:

<table id="grid_name" cellpadding="0" cellspacing="0"></table>
<div id="pager2" class="scroll" style="text-align: center;"></div>

Hope this looks very easy to integrate with CI. Enjoy 🙂

Display Unicode in JavaScripts using Jquery

Last time, I faced a problem with alerting HTML unicode characters in JavaScript.  It runs correctly in html code but rise problem while it is between script tag. Then I found a solution by embedding HTML <DIV> element with unicode using Jquery.

<script type="text/javascript">

        $(document).ready(function() {

                $("a#remove").click(function() {

                        $("#msg").html("Unicode here");
                        return confirm($("#msg").html());

                });

        });

</script>

<div id="msg" style="display:none"></div>
<a href="#"  id="remove">Remove</a>

Now its working nice 🙂

Life With JQGrid

I ‘m a beginner in Jquery. As the time I am passing with Jquery, It’s making my life so simple and easier because I was always afraid of Ajax. jQuery is a fast and well organized JavaScript Library who has the slogan “Write less, Read more”.

Recently I worked with its grid system JQgrid. When I worked with that, I found that pretty interesting. That’s really Cool :).

Link for JQGrid demo: http://www.trirand.com/jqgrid/jqgrid.html

Now I’m playing with this tool and enjoying a lot……