Saturday, 26 December 2015

Codeigniter Categories sub categories dictionary

Some times you want categoriesOr i can say that a dictionary which needs to be fetch from mysql , there for all links , content will be fetch from database mysql by creating a singel view file with support of jQuery for processing menus. There will be your Administration OR Admin panelwho will create these categories , sub categories.
 
1.Your Controller functions will goes like below.
  1. defined('BASEPATH') OR exit('No direct script access allowed');
  2. class School extends MY_Controller {
  3. public function __construct() {
  4. parent::__construct();
  5. }
  6. public function get_dictionary() {
  7. $this->load->model('schools');
  8. $this->load->model('trading_tools');
  9. $data['meta_title'] = 'School';
  10. $data['meta_keywords'] = 'School';
  11. $data['meta_desc'] = 'School';
  12. $data['signup_signin_model'] = 'root/signin_up_model_html';
  13. $parent_slug = trim($this->uri->segment(2));
  14. $child_slug = trim($this->uri->segment(3));
  15. if (isset($child_slug) && $child_slug != '') {
  16. $data = array($child_slug);
  17. $where = 'slug_name';
  18. $data['school_info'] = $this->schools->get_records_where_in('schools_category', $where, $data);
  19. } else {
  20. $data['school_info'] = $this->schools->get_school_info($parent_slug);
  21. }
  22. $menu = $this->trading_tools->get_items();
  23. $data['side_bar_menu'] = $this->buildMenu(0, $menu);
  24. $data['loginheader'] = '';
  25. $data['top_header'] = 'root/top_header';
  26. $data['top_menu'] = 'root/top_menu';
  27. $data['parent_slug_name'] = $parent_slug;
  28. $data['child_slug_name'] = $child_slug;
  29. if ($parent_slug != 'glossary') {
  30. $data['main'] = 'root/school_child';
  31. } else {
  32. $data['main'] = 'root/school_glossary';
  33. }
  34. $data['footer'] = 'root/footer';
  35. $this->load->vars($data);
  36. $this->load->view($this->template);
  37. }
  38. public function buildMenu($parent, $menu) {
  39. $html = "";
  40. if (isset($menu['parent_menus'][$parent])) {
  41. if ($parent <= 0)
  42. $html .= "<ul class='nav nav-pills nav-stacked' style='background:#E9E9E9;'>";
  43. else
  44. $html.= '<ul class="dropdown-menu">';
  45. $countfor_active = 0;
  46. foreach ($menu['parent_menus'][$parent] as $menu_id) {
  47. $li_parentclass = '';
  48. $ul_inside_li = '<ul class="dropdown-menu ' . $menu['menus'][$menu_id]['slug_name'] . '>';
  49. if ($countfor_active == 0) {
  50. $li_parentclass = 'dropdown ' . $menu['menus'][$menu_id]['slug_name'] . '';
  51. }
  52. if (!isset($menu['parent_menus'][$menu_id])) {
  53. $html .= "<li class='" . $li_parentclass . "'>
  54. <a href='" . $menu['menus'][$menu_id]['page_link'] . "'>
  55. " . $menu['menus'][$menu_id]['category_name'] . "</a></li>";
  56. }
  57. if (isset($menu['parent_menus'][$menu_id])) {
  58. $html .= "<li class='" . $li_parentclass . "'>
  59. <a href='" . $menu['menus'][$menu_id]['page_link'] . "'> <i
  60. class='fa fa-angle-right pull-right'></i>
  61. " . $menu['menus'][$menu_id]['category_name'] . "</a>";
  62. $html .= $this->buildMenu($menu_id, $menu);
  63. $html .= "</li>";
  64. }
  65. }
  66. $html .= "</ul>";
  67. }
  68. return $html;
  69. }
  70. }
2. Basically i am using two views filesbecause layout OR html is different for both. One view file will contain Dictionary (school_glossary) and sencond view (school_child) file will contain simple content to display.
 
A) school_glossary View
  1. <div class="l-main-container">
  2. <div class="b-breadcrumbs f-breadcrumbs">
  3. <div class="container">
  4. <ul>
  5. <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown"
  6. href="#"><i class="fa fa-home"></i>Home</a></li>
  7. <li><i class="fa fa-angle-right"></i><a href="#">Forex Tools</a></li>
  8. <li><i class="fa fa-angle-right"></i><span>Forex School</span></li>
  9. </ul>
  10. </div>
  11. </div>
  12. <div class="l-inner-page-container">
  13. <div class="container">
  14. <div class="row">
  15. <div class="col-md-9 col-md-push-3">
  16. <div class="b-shortcode-example">
  17. <div class="b-tabs f-tabs j-tabs b-tabs-reset ui-tabs ui-widget ui-widget-content ui-corner-all">
  18. <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix
  19. ui-widget-header ui-corner-all" role="tablist">
  20. <?php if (count($school_info) > 0) { ?>
  21. <?php
  22. $alphabet = array('A'=>'glossary-a','B'=>'glossary-b','C'=>'glossary-c','D'=>'glossary-d',
  23. 'E'=>'glossary-e','F'=>'glossary-f','G'=>'glossary-g','H'=>
  24. 'glossary-h','I'=>'glossary-i','J'=>'glossary-j','K'=>'glossary-k',
  25. 'L'=>'glossary-l','M'=>'glossary-m','N'=>'glossary-n','O'=>
  26. 'glossary-o','P'=>'glossary-p','Q'=>'glossary-q','R'=>'glossary-r','S'=>'glossary-s'
  27. ,'T'=>'glossary-t','U'=>'glossary-u','V'=>'glossary-v','W'=>'glossary-w',
  28. 'X'=>'glossary-x','Y'=>'glossary-y','Z'=>'glossary-z');
  29. foreach ($school_info as $key => $value) {?>
  30. <li class="ui-state-default ui-corner-top" role="tab" tabindex="-1"
  31. aria-controls="tabs-21" aria-labelledby="ui-id-1" aria-selected="false" aria-expanded="false">
  32. <a href="#tabs-<?php echo $school_info[$key]->s_category_id;?>"
  33. class="ui-tabs-anchor" role="presentation" tabindex="-1"
  34. id="ui-id-<?php echo $school_info[$key]->s_category_id;?>">
  35. <?php foreach ($alphabet as $al => $alp) {?>
  36. <?php if($alp==$school_info[$key]->slug_name){ ?>
  37. <?php echo $al; ?>
  38. <?php }?>
  39. <?php }?>
  40. </a>
  41. </li>
  42. <?php } ?>
  43. <?php }?>
  44. </ul>
  45. <div class="b-tabs__content">
  46. <?php if (count($school_info) > 0) { ?>
  47. <?php foreach ($school_info as $key => $value) {?>
  48. <div id="tabs-<?php echo $school_info[$key]->s_category_id;?>"
  49. aria-labelledby="ui-id-<?php echo $school_info[$key]->s_category_id;?>"
  50. class="ui-tabs-panel ui-widget-content ui-corner-bottom" role="tabpanel"
  51. aria-hidden="true" style="display: none;">
  52. <?php echo html_entity_decode($school_info[$key]->page_body); ?>
  53. </div>
  54. <?php }?>
  55. <?php }?>
  56. </div>
  57. </div>
  58. </div>
  59. </div>
  60. <div class="visible-xs-block visible-sm-block b-hr"></div>
  61. <div class="col-md-3 col-md-pull-9">
  62. <?php if (isset($side_bar_menu)) { ?>
  63. <?php echo $side_bar_menu; ?>
  64. <?php } ?>
  65. </div>
  66. </div>
  67. </div>
  68. </div>
  69. </div>
  70. <script>
  71. $(document).ready(function () {
  72. var p_slug_name=".<?php echo $parent_slug_name;?>";
  73. $(".nav").find(p_slug_name).addClass('active');
  74. });
  75. </script>
B) school_child View
  1. <div class="l-main-container">
  2. <div class="b-breadcrumbs f-breadcrumbs">
  3. <div class="container">
  4. <ul>
  5. <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown"
  6. href="#"><i class="fa fa-home"></i>Home</a></li>
  7. <li><i class="fa fa-angle-right"></i><a href="#">Forex Tools</a></li>
  8. <li><i class="fa fa-angle-right"></i><span>Forex School</span></li>
  9. </ul>
  10. </div>
  11. </div>
  12. <div class="l-inner-page-container">
  13. <div class="container">
  14. <div class="row">
  15. <?php if (count($school_info) > 0) { ?>
  16. <div class="col-md-9 pull-right"><h4><?php echo $school_info[0]->category_name;?></h4></div>
  17. <?php } ?>
  18. <div class="col-md-9 col-md-push-3">
  19. <div class="b-blog-listing__block">
  20. <div class="b-blog-listing__block-top"> </div>
  21. <div class="b-infoblock-with-icon b-blog-listing__infoblock">
  22. <div class="b-infoblock-with-icon__info f-infoblock-with-icon__info">
  23. <?php if (count($school_info) > 0) { ?>
  24. <?php echo html_entity_decode($school_info[0]->page_body); ?>
  25. <?php } ?>
  26. </div>
  27. </div>
  28. </div>
  29. </div>
  30. <div class="visible-xs-block visible-sm-block b-hr"></div>
  31. <div class="col-md-3 col-md-pull-9">
  32. <?php if (isset($side_bar_menu)) { ?>
  33. <?php echo $side_bar_menu; ?>
  34. <?php } ?>
  35. </div>
  36. </div>
  37. </div>
  38. </div>
  39. </div>
  40. <script>
  41. $(document).ready(function () {
  42. var p_slug_name=".<?php echo $parent_slug_name;?>";
  43. $(".nav").find(p_slug_name).addClass('active');
  44. });
  45. </script>
3. Your model function will goes like below
  1. class Schools extends CI_Model {
  2. function __construct() {
  3. // Call the Model constructor
  4. parent::__construct();
  5. $this->load->library('session');
  6. $this->load->database();
  7. }
  8. function get_school_info($parent_slug){
  9. $q_school="select * from cbf_schools_category where parentid =(select s_category_id
  10. from cbf_schools_category where slug_name='".$parent_slug."')";
  11. $query=$this->db->query($q_school);
  12. if ($query->num_rows() > 0)
  13. return $query->result();
  14. else
  15. $q_get_main="select * from cbf_schools_category where slug_name='".$parent_slug."'";
  16. $query1=$this->db->query($q_get_main);
  17. return $query1->result();
  18. }
  19. function get_records_where_in($table, $where, $data) {
  20. $this->db->where_in($where, $data);
  21. $query = $this->db->get($table);
  22. if ($query->num_rows() > 0)
  23. return $query->result();
  24. else
  25. return NULL;
  26. }
  27. }
4. You will need to define a routes in your routes.php
  1. $route['school/(:any)'] = 'school/get_dictionary/$1';
5. Your Mysql table goes like below which will contain parent , child relationship in single table.

Monday, 30 November 2015

Install and Run Tomcat windows

I am explaining every step to run tomcat in window and how to setup your projects and running Servlets.

1. Install JDK before installing tomcat.

  a) I installed JDK1.6.0 onC:\Java\jdk1.6.0

NOTE: Do not installed JDK under C:\Program Files. I just faced problem after setting my
environment variable on Window Xp.

2. Download the latest version of tomcat.
tomcat.apache.org , i downloaded Apache Tomcat 7.0.65.I rename downloaded folder to "apache-tomcat" and placed it at E:\apache-tomcat.Go to "Start" --> "My Computer" --> Right click--> "Property"--> Click "Advance Tab" --> "Environment Variables" --> Opens a window where you have to create new Environment Variables As Written Below
  1. /* Under User Variable click New */
  2. Variable Name CATALINA_HOME
  3. Variable Value E:\apache-tomcat , Press ok
  4. Variable Name JAVA_HOME
  5. Variable Value C:\Java\jdk1.6.0, Press ok
  6. Variable Name JAVA_HOME
  7. Variable Value C:\Java\jdk1.6.0, Press ok
  8. Variable Name PATH
  9. Variable Value C:\Java\jdk1.6.0\bin, Press ok
  10. // Under System Variable click New
  11. Variable Name CALSSPATH
  12. Variable Value C:\Java\jdk1.6.0\bin;E:\apache-tomcat\lib\servlet-api.jar, Press ok
3. Now We have to edit configuration files E:\apache-tomcat\conf folder
  1. Open file context.xml find line/xml tag <Context>
  2. and replace by <Context reloadable="true">
  3. <servlet>...</servlet> inside this tag find
  4. <param-value>false</param-value>
  5. and replace with <param-value>true</param-value>
  6. Open file tomcat-users.xml and placed below code inside<tomcat-users>...</tomcat-users>
  1. <role rolename="manager-gui"/>
  2. <role rolename="admin-gui"/>
  3. <user username="boy108zon" password="boy108zon" roles="manager-gui,admin-gui"/>
4.Restart your computer. After above steps configuration. Lets create a new project.

1. I created a folder called store in E:\apache-tomcat\webapps\
2. Create Structure under
  1. store(Project Folder) ---> WEB-INF(DIR) --> classes(DIR) , web.xml (FILE)
  2. classes(DIR)-->HelloWorld.java (File)
3. Placed below xml code in web.xml created as above
  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  3. "http://java.sun.com/dtd/web-app_2_3.dtd">
  4. <web-app>
  5. <servlet>
  6. <servlet-name>HelloWorld</servlet-name>
  7. <servlet-class>HelloWorld</servlet-class>
  8. </servlet>
  9. <servlet-mapping>
  10. <servlet-name>HelloWorld</servlet-name>
  11. <url-pattern>/</url-pattern>
  12. </servlet-mapping>
  13. </web-app>
4. Open http://localhost:8080/ You can see Tomcat Statup Page , you can click on Mange App it will ask you to enter username and password , As you putted OR placed in tomcat-users.xml.
 
Here you can see list of Application running or deploy. if you further check our created application also visible to this list , you can Start , Stop , Reload , Undeploy your application here. Click on start so that our created application can be start.
 
5. That's all , Now open http://localhost:8080/store/ and you will see your HelloWorld Running.

Saturday, 28 November 2015

Carousel slider codeigniter mysql

You may also see the post here http://yourlearn.in/posts/view/1/bootstrap-carousel-thumbnail-slider and know and read much more about it.

 
 
 
If you want to implement Bootstrap Carousel Thumbnail Slider with Codeigniter, follow the steps
1.Your html file or you can say your view file will goes like below.
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>Bootstrap Example</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  8. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  9. <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  10. <style>
  11. .carousel-inner > .item > img,
  12. .carousel-inner > .item > a > img {
  13. width: 70%;
  14. margin: auto;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="container">
  20. <div id="slider-property" class="carousel slide" data-ride="carousel">
  21. <!-- Indicators -->
  22. <ol class="carousel-indicators">
  23. <?php echo $indicators; ?>
  24. </ol>
  25.  
  26. <!-- Wrapper for slides -->
  27. <div class="carousel-inner" role="listbox">
  28. <?php echo $slides; ?>
  29. </div>
  30.  
  31. <!-- Left and right controls -->
  32. <a class="left carousel-control" href="#slider-property" role="button" data-slide="prev">
  33. <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
  34. <span class="sr-only">Previous</span>
  35. </a>
  36. <a class="right carousel-control" href="#slider-property" role="button" data-slide="next">
  37. <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
  38. <span class="sr-only">Next</span>
  39. </a>
  40. </div>
  41. </div>
  42. </div>
  43. </body>
  44. </html>
2. Your controller function will goes like below
  1. class Welcome extends CI_Controller {
  2. public function index(){
  3. }
  4. public function get_all_images(){
  5. $this->load->model('carsol');
  6. $query = $this->carsol->get_all_images();
  7. $count = count($query);
  8. $indicators = '';
  9. $slides = '';
  10. $counter = 0;
  11. foreach($query AS $key => $value){
  12. $image = $query[$key]['theme_thumb'];
  13. $title = $query[$key]['theme_title'];
  14. if ($counter == 0) {
  15. $indicators .= '<li data-target="#slider-property" data-slide-to="' . $counter . '"
  16. class="active"></li>';
  17. $slides .= '<div class="item active">
  18. <img src="http://localhost/CI2.1.4/images/thumbnail/' . $image . '" alt="' . $title . '"/>
  19. </div>';
  20. } else {
  21. $indicators .= '<li data-target="#slider-property"
  22. data-slide-to="' . $counter . '"></li>';
  23. $slides .= '<div class="item">
  24. <img src="http://localhost/CI2.1.4/images/thumbnail/' . $image . '" alt="' . $title . '"/>
  25. </div>';
  26. }
  27. $counter=$counter+1;
  28. }
  29. $data['indicators'] = $indicators;
  30. $data['slides'] = $slides;
  31. $this->load->view('carsol', $data);
  32. }
  33. }
3. Your model function will goes like below
  1. class Carsol extends CI_Model {
  2. function __construct() {
  3. // Call the Model constructor
  4. parent::__construct();
  5. $this->load->database();
  6. }
  7. function get_all_images(){
  8. $query = $this->db->query("SELECT * FROM theme_themes where category_id =3 limit 4");
  9. return $query->result_array();
  10. }
  11. }

Tuesday, 24 November 2015

Multiple records delete datatables ajax

If you want to implement add bulk action like Export CSV , Removing all , single records , Export seleted records to excel and adding filters like days filter to data tables listings using ajax approch 1. You need to include required jQuery for datatables , ajax processing.
  1. <script src="<?php echo base_url(); ?>assets/js/jquery-1.11.0.min.js"></script>
  2. <script src="<?php echo base_url(); ?>assets/js/jquery.dataTables.min.js"></script>
  3. <script src="<?php echo base_url(); ?>assets/js/dataTables.bootstrap.js"></script>
  4. <script src="<?php echo base_url();?>assets/js/datatables/responsive/js/datatables.responsive.js">
  5. </script>
  6. <script src="<?php echo base_url(); ?>assets/js/datatables/jquery.dataTables.columnFilter.js">
  7. </script>
2. Your html source file or you can say your view file will goes like below.
  1. <h3 class="page-title">Accounts</h3>
  2. <div class="panel panel-primary" data-collapsed="0">
  3. <div class="col-sm-12">
  4. <div class="panel-body">
  5. <form id="Gexcel" name="Gexcel" method="POST" action="<?php echo base_url(); ?
  6. >accounts/create_document">
  7. <input type="hidden" name="aidds" id="aidds" ><input type="hidden" name="atype" id="atype" value="da" >
  8. </form>
  9. <table id="demo_account_listing" class="display" cellspacing="0" width="100%">
  10. <thead>
  11. <tr>
  12. <th class="no-sort"></th>
  13. <th class="trigger_reload">Sr No</th>
  14. <th>ID</th>
  15. <th>Date</th>
  16. <th class="no-sort">Days Left</th>
  17. <th>Name</th>
  18. <th>Email Address</th>
  19. <th>Country</th>
  20. <th>Phone</th>
  21. <th>Mobile</th>
  22. <th>Photo</th>
  23. <th>Source</th>
  24. <th class="no-sort"> Action</th>
  25. </tr>
  26. </thead>
  27. </table>
  28. </div>
  29. </div>
  30. </div>
  31. <script type="text/javascript">
  32. jQuery(window).load(function () {
  33. var $ = jQuery;
  34. var oAllLinksTable = $("#demo_account_listing").dataTable({
  35. "bProcessing": true,
  36. "bServerSide": true,
  37. "sAjaxSource": baseurl + 'accounts/get_account_listing',
  38. "sPaginationType": "bootstrap",
  39. "oLanguage": {
  40. "sEmptyTable": "No account found.",
  41. "sProcessing": "<img src='<?php echo base_url(); ?>/assets/global/img/loading-spinner-blue.gif'>"
  42. },
  43. "columnDefs": [{
  44. "targets": 'no-sort',
  45. "orderable": false
  46. }],
  47. "aoColumnDefs": [{"bVisible": true, "aTargets": [0]}],
  48. "order": [[0, "desc"]],
  49. processing: true,
  50. "fnServerParams": function (aoData) {
  51. var last_days = $('input[name=days_filter]:checked').val();
  52. aoData.push({name: "days_filter", value: last_days});
  53. },
  54. "fnRowCallback": function (nRow, aData, iDisplayIndex) {
  55. var oSettings = oAllLinksTable.fnSettings();
  56. $("td:nth-child(2)", nRow).html(oSettings._iDisplayStart + iDisplayIndex + 1);
  57. $(nRow).attr("id", 'tr_' + aData[0]);
  58. $("td:nth-child(1)", nRow).html("
  59. <input type='checkbox' name='contacts[]' class='mail-checkbox check_' value='" + aData[0] + "'>");
  60. return nRow;
  61. }
  62. });
  63. var action_radio = '<div class="pull-right check_filter" id="filter_group_radio"><span>
  64. <input type="radio" name="days_filter" id="dsv" class="form-control days_filter" value="7">
  65. Last7 Days</span>&nbsp;<span>
  66. <input type="radio" id="df" name="days_filter" class="form-control days_filter" value="14">
  67. Last 14 Days &nbsp;</span><span>
  68. <input type="radio" id="dthi" name="days_filter" class="form-control days_filter" value="30">
  69. Last 30 Days&nbsp;</span><span>
  70. <input type="radio" id="dsx" name="days_filter" class="form-control days_filter" value="60">
  71. Last 60 Days</span></div>';
  72. var extra_action = action_radio + '<div class="pull-right">
  73. <a href="<?php echo base_url(); ?>accounts/new_account">
  74. <button class="btn purple-plum pull-right" type="button">Open New Demo Account</button>
  75. </a>&nbsp;</div>';
  76. $custome_search_filter = extra_action + ' <span class="btn blue" style="height:34px;">
  77. <input type="checkbox" class="checkallbox" id="select_all_"></span><div class="pull-right">
  78. <div class="btn-group myremove"><button data-toggle="dropdown"
  79. class="btn blue dropdown-toggle dropup" aria-expanded="false">
  80. Bulk Action<i class="fa fa-angle-down"></i></button><ul role="menu"
  81. class="dropdown-menu pull-right">
  82. <li role="presentation"><a data-toggle="modal" class="deleteRecord"
  83. href="" tabindex="-1" role="menuitem">
  84. Delete</a></li><li role="presentation">
  85. <a data-toggle="modal" class="exportExcel" href="" tabindex="-1"
  86. role="menuitem">Export to excel</a></li></ul></div></div>';
  87. $($custome_search_filter).appendTo("#demo_account_listing_length > label");
  88. $("#demo_account_listing_length").parent().removeClass('col-md-6').addClass('col-md-10');
  89. $("#demo_account_listing_filter").parent().removeClass('col-md-6').removeClass('col-sm-12');
  90. $(function () {
  91. $(document).on('change', '.days_filter', function (event) {
  92. event.preventDefault();
  93. oAllLinksTable.fnFilter(this.value, 12);
  94. $(this).find('#filter_group_radio input:radio').prop('checked', true);
  95. });
  96. });
  97. $(document).on('click', '.checkallbox', function () {
  98. if ($('#select_all_').is(':checked')) {
  99. $(".check_").prop("checked", "checked");
  100. } else {
  101. $(".check_").removeAttr('checked');
  102. }
  103. });
  104. $(document).on('click', '.check_', function () {
  105. var $this = $(this);
  106. // $this will contain a reference to the checkbox
  107. var numberOfChecked = $('.check_:checked').length;
  108. var totalCheckboxes = $('.check_').length;
  109. var numberNotChecked = totalCheckboxes - numberOfChecked;
  110. if (numberOfChecked == totalCheckboxes) {
  111. $('#select_all_').prop('checked', 'checked');
  112. }
  113. else {
  114. $('#select_all_').removeAttr('checked');
  115. }
  116. });
  117. $(document).on('click', '.deleteRecord', function (e) {
  118. e.preventDefault();
  119. var allVals = [];
  120. $('.check_').each(function () {
  121. if ($(this).is(':checked')) {
  122. allVals.push($(this).val());
  123. }
  124. });
  125. if ($('.check_').is(':checked')) {
  126. bootbox.confirm("Are you sure you want to delete?", function (result) {
  127. if (result == true) {
  128. $.ajax({
  129. url: baseurl + 'accounts/removeAccounts?time=' + timestamp,
  130. type: 'post',
  131. data: 'atype=la&rids=' + allVals,
  132. dataType: 'json',
  133. success: function (response) {
  134. $("#showmessage_jscbf").html("");
  135. switch (response.Mstatus) {
  136. case 'success':
  137. $.each(response.idds.split(','), function () {
  138. $("#tr_" + this).hide();
  139. });
  140. $(".trigger_reload").trigger('click');
  141. break;
  142. case 'error':
  143. $("#showmessage_jscbf").html(response.msg);
  144. break;
  145. }
  146. }
  147. });
  148. }
  149. });
  150. return false;
  151. } else {
  152. alert("Please select one record to delete.")
  153. }
  154. });
  155. $(document).on('click', '.exportExcel', function (e) {
  156. e.preventDefault();
  157. var allVals = [];
  158. $('.check_').each(function () {
  159. if ($(this).is(':checked')) {
  160. allVals.push($(this).val());
  161. }
  162. });
  163. if ($('.check_').is(':checked')) {
  164. $("#aidds").val(allVals);
  165. document.Gexcel.submit();
  166. } else {
  167. alert("Please select one records to export.")
  168. }
  169. });
  170. });
  171. $(function () {
  172. $(document).on('click', '.removeRcords', function (event) {
  173. event.preventDefault();
  174. var idss = $(this).attr('id');
  175. var rid = idss.split("_")[1];
  176. do_remove_ajax('account_type_remove', rid);
  177. });
  178. });
  179. </script>
Notes:
I. Gexcel is a form where all selected ids will be store in hidden id aidds textbox.
II. demo_account_listing_length , you can just open your firebug and can get your id from there.you can see in above html that my id is demo_account_listing so datatable attaching his event to this id.
III. action_radio , $custome_search_filter , extra_action is the filter html , we have to inject to datatables.
IV. fnRowCallback function is a datatable function , i have to put s.no there also $("td:nth-child(1)", nRow) is checkbox which will inject with primary key of your table in mysql.
V. bootbox.confirm is alert box , you can replace simple confim alert box of javascript if you don't need.
VI. $.each(response.idds.split(','), function () { $("#tr_" + this).hide();}); from ajax response comma seperated ids will be revert back from your controller.
3. Your controller function will go like below
  1. public function get_account_listing() {
  2. $this->load->model('common');
  3. $aColumns = array('id', 'id', 'account_no', 'regdate', 'daysleft', 'name', 'email',
  4. 'country', 'mobile', 'leverage', 'balance', 'lead_source');
  5. $aColumnsWhere = array('a.id', 'a.account_no', 'a.date_time', 'a.email', 'a.leverage', 'a.balance',
  6. 'da.firstname', 'da.lastname', 'da.regdate', 'da.mobile', 'c.country_name', 'da.lead_source');
  7. $sIndexColumn = "id";
  8. $sTable = "account";
  9. //custome filter
  10. $days_filter = (int) $this->input->get('days_filter', TRUE);
  11. $iDisplayStart = $this->input->get('iDisplayStart', true);
  12. $iDisplayLength = $this->input->get('iDisplayLength', true);
  13. $iSortCol_0 = $this->input->get('iSortCol_0', true);
  14. $iSortingCols = $this->input->get('iSortingCols', true);
  15. $sLimit = "";
  16. if (isset($iDisplayStart) && $iDisplayLength != '-1') {
  17. $sLimit = "LIMIT " . $iDisplayStart . ", " .
  18. $iDisplayLength;
  19. }
  20. if (isset($iSortCol_0)) {
  21. $sOrder = "ORDER BY ";
  22. for ($i = 0; $i < intval($iSortingCols); $i++) {
  23. if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
  24. $sOrder .= $aColumns[intval($_GET['iSortCol_' . $i])] . "
  25. " . trim($_GET['sSortDir_' . $i]) . ", ";
  26. }
  27. }
  28. $sOrder = substr_replace($sOrder, "", -2);
  29. if ($sOrder == "ORDER BY") {
  30. $sOrder = "";
  31. }
  32. }
  33. $sSearch = $this->input->get('sSearch', true);
  34. $sWhere = "";
  35. if ($sSearch != "") {
  36. $sWhere = "AND (";
  37. for ($i = 0; $i < count($aColumnsWhere); $i++) {
  38. $sWhere .= $aColumnsWhere[$i] . " LIKE '%" . $sSearch . "%' OR ";
  39. }
  40. $sWhere = substr_replace($sWhere, "", -3);
  41. $sWhere .= ')';
  42. }
  43. if ($days_filter != '') {
  44. $sWhere .= "AND (";
  45. $sWhere .= '' . $aColumnsWhere[2] . ' BETWEEN DATE_SUB(NOW(),INTERVAL ' . $days_filter . ' DAY) AND
  46. NOW()';
  47. //$sWhere .= 'DATE('.$aColumnsWhere[12].')' . " BETWEEN
  48. '" . DATE('Y-m-d',strtotime($start_date)) . "' AND '".DATE('Y-m-d',strtotime($end_date))."'";
  49. $sWhere .= ')';
  50. }
  51. /* Individual column filtering */
  52. for ($i = 0; $i < count($aColumns); $i++) {
  53. if ($_GET['bSearchable_' . $i] == "true" && $_GET['sSearch_' . $i] != '') {
  54. if ($sWhere == "") {
  55. $sWhere = " WHERE ";
  56. } else {
  57. $sWhere .= " AND ";
  58. }
  59. $sWhere .= $aColumns[$i] . " LIKE '%" . trim($_GET['sSearch_' . $i]) . "%'";
  60. }
  61. }
  62. $sEcho = $this->input->get('sEcho');
  63. $result = $this->common->demo_account_listing($sTable, $sWhere, $sOrder, $sLimit,
  64. $aColumns, $sIndexColumn, $sEcho);
  65. echo json_encode($result);
  66. }
4. Your model code goes like below
  1. function demo_account_listing($sTable, $sWhere, $sOrder,$sLimit, $aColumns, $sIndexColumn, $sEcho){
  2. $sJoin_q_fields = "SELECT SQL_CALC_FOUND_ROWS a.id,a.account_no,a.date_time,
  3. a.email,a.leverage,a.balance, da.regdate, da.firstname as name,
  4. da.mobile, c.country_name as country, da.lead_source";
  5. $sJoin_q = " FROM (account a)";
  6. $sJoin_q .= ' INNER JOIN demo_register da ON a.email = da.email';
  7. $sJoin_q .= ' INNER JOIN country c ON da.country = c.id';
  8. $sJoin_q .= ' WHERE a.act_type = "ABC" ';
  9. $qJoin = $sJoin_q_fields . $sJoin_q . ' ' . $sWhere . ' ' . $sOrder . ' ' . $sLimit;
  10. $rResult = $this->db->query($qJoin);
  11. $rResult_array = $rResult->result_array();
  12. $iFilteredTotal = count($rResult_array);
  13. /* Total data set length */
  14. $sJoin_q_count = "SELECT COUNT(" . $sIndexColumn . ") AS TotalRecords";
  15. $sQuery_TR = $sJoin_q_count . $sJoin_q.$sWhere;
  16. $rResult_TR = $this->db->query($sQuery_TR);
  17. $rResult_array_TR = $rResult_TR->result_array();
  18. $iTotal = $rResult_array_TR[0]['TotalRecords'];
  19. $output = array(
  20. "sEcho" => intval($sEcho),
  21. "iTotalRecords" => intval($iTotal),
  22. "iTotalDisplayRecords" => intval($iTotal), //$iFilteredTotal,
  23. "aaData" => array()
  24. );
  25. $i = 0;
  26. $last = intval($iTotal);
  27. $seclast = intval($iTotal) - 1;
  28. foreach ($rResult_array as $aRow) {
  29. $row = array();
  30. foreach ($aColumns as $col) {
  31. if ($col == 'daysleft') {
  32. $rem = $this->ref_time - strtotime($aRow['regdate']);
  33. $row[] = 30 - floor($rem / 86400);
  34. } else if ($aRow[$col] == 'D') {
  35. $row[] = '<a href="javascript:void(0)" id="E_' . $aRow['id'] . '" name=""
  36. class="btn btn-success btn-sm "><i class="entypo-check"></i> Enable</a>';
  37. } else if ($aRow[$col] == 'E') {
  38. $row[] = '<a href="javascript:void(0)" id="D_' . $aRow['id'] . '"
  39. name="broker_account_status_request_ed" class="btn btn-danger btn-sm ">
  40. <i class="entypo-minus"></i> Disable</a>';
  41. } else {
  42. $row[] = $aRow[$col];
  43. }
  44. }
  45. $i++;
  46. if ($i == $last || $i == $seclast) {
  47. $classaction = 'dropup';
  48. } else {
  49. $classaction = '';
  50. }
  51. array_push($row, '<div class="btn-group ' . $classaction . ' ">
  52. <button data-toggle="dropdown" class="btn red dropdown-toggle" aria-expanded="false">Action
  53. <i class="fa fa-angle-down"></i>
  54. </button>
  55. <ul role="menu" class="dropdown-menu pull-right">
  56. <li role="presentation">
  57. <a href="' . base_url() . 'accounts/change_mt4_pw/' . $aRow['id'] . '" tabindex="-1" role="menuitem">
  58. Change Password
  59. </a>
  60. </li>
  61. <li role="presentation">
  62. <a href="' . base_url() . 'accounts/delete_account/' . $aRow['id'] . '" tabindex="-1" role="menuitem">
  63. Delete Account
  64. </a>
  65. </li>
  66. <li role="presentation">
  67. <a href="' . base_url() . 'accounts/link_account/' . $aRow['id'] . '" tabindex="-1" role="menuitem">
  68. Link Account
  69. </a>
  70. </li>
  71. </ul>
  72. </div>');
  73. $output['aaData'][] = $row;
  74. }
  75. return $output;
  76. }
5. Your view load function will goes like below
  1. public function index() {
  2. $data['meta_title'] = 'Accounts';
  3. $data['meta_keywords'] = 'Accounts';
  4. $data['meta_desc'] = 'Accounts';
  5. $data['top_mobile_menu'] = 'admin/dashboard/top_mobile_menu';
  6. $data['top_menu'] = 'admin/dashboard/top_menu';
  7. $data['main'] = 'admin/dashboard/accounts/account_listing';
  8. $data['footer'] = 'admin/dashboard/footer';
  9. $this->load->vars($data);
  10. $this->load->view($this->admin_dashboard);
  11. }
6. Your function for exporting i am using dompdf library for codeigniter. you can get it after googling.
  1. public function create_document() {
  2. $this->load->helper('dompdf');
  3. $this->load->helper('file');
  4. $this->load->model('prints');
  5. $account_ids = $this->input->post('aidds');
  6. $account_type = $this->input->post('atype');
  7. $result = $this->prints->print_account_listing(format_in_clause($account_ids));
  8. if (!empty($result)) {
  9. $this->load->library('excel');
  10. $this->excel->to_excel($result, "Aaccount-Listing");
  11. exit;
  12. } else {
  13. $this->session->set_flashdata('msg',
  14. alertmessage($message_type = 'alert-danger', $message = 'Unable to process your requiest.'));
  15. redirect(base_url() . 'accounts');
  16. }
  17. }
7. Your function for removing records.
  1. public function removeAccounts() {
  2. $this->load->model('common');
  3. $id = trim($this->input->post('rids'));
  4. $account_type = trim($this->input->post('atype'));
  5. if (isset($id)) {
  6. $thread_ids = explode(",", $id);
  7. foreach ($thread_ids as $values) {
  8. $this->common->do_remove_records('account', array('id' => $values, 'act_type' => 'DEMO'));
  9. }
  10. echo json_encode(array('Mstatus' => 'success', 'idds' => $id,
  11. 'msg' => alertmessage($message_type = 'alert-success', $message = 'Accounts has been removed.')));
  12. } else {
  13. echo json_encode(array('Mstatus' => 'error',
  14. 'msg' => alertmessage($message_type = 'alert-danger', $message = 'Error in process. Try later.')));
  15. }
  16. }
  17. 8. alertmessage is a helper function for generating bootstrap message.
  18. function alertmessage($message_type, $message) {
  19. $output = '';
  20. if (!empty($message_type) && !empty($message)) {
  21. $output.="<div class='alert showmessage_jscbf " . $message_type . "'>" . $message . "</div>";
  22. return $output;
  23. } else {
  24. return $output;
  25. }
  26. }
9. format_in_clause is a helper function.
  1. function format_in_clause($string) {
  2. if (isset($string)) {
  3. $realArray = explode(',', $string);
  4. if (is_array($realArray)) {
  5. $stringForIn = "'" . implode("','", $realArray) . "'";
  6. return $stringForIn;
  7. } else {
  8. return $string;
  9. }
  10. } else {
  11. return NULL;
  12. }
  13. }

Tuesday, 10 November 2015

Neteller payment integration core Php , Curl.

You may also see the post here https://yourlearn.in/posts/view/6/neteller-payment-integration-core-php and know and read much more about it.


If you want to implement Neteller payment using Core / Simple Php below is code for you can get it. I have used below code for only testing purpose so i can check weather Neteller working OR not. Please never used below code on production if you want to use below code in production you have to modify it accordingly like.
 
You can create function for CURL request , passing merchant info in hidden field is not good way you can take that in your PHP SCRIPT.
 
To set up a Business Test Account, you need to provide the below information to merchantsupport@paysafe.com and they`ll set it up for you
  1. Merchant descriptor name: Your descriptor name
  2. Contact Person: Your Name
  3. Phone number: Your Number
  4. Country: Your Country
  5. Contact E-mail: create an email on gmail , yahoo...etc and put here.
  6. Currency Accounts: Your Currency USD..etc
 
You can find Member Test Accounts in the Integration Manual on page 153.
 
You can go to https://merchant.neteller.com/merchflux/public/index and grab your merchant info and replace in hidden field. You have to request there customer support for enabling API client key and secret key for testing purpose. During my code testing i found invalid client issue response from API so for issue i have to add IP address there. Another issue i have faced minimum amount , Amount should be passed as $_POST['amount']*100.
 
1. Your All Php , Html Code file or you can say your view file will goes like below.
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  2. "http://www.w3.org/TR/html4/loose.dtd">
  3. <html>
  4. <head>
  5. <title>NETELLER</title>
  6. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  7. </head>
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  9. "http://www.w3.org/TR/html4/loose.dtd">
  10. <html>
  11. <head>
  12. <title>NETELLER</title>
  13. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  14. </head>
  15. <body>
  16. <form method="post" action=""><br>
  17. Version: <input type="text" name="version" value="4.1"><br>
  18. Amount : <input type="text" name="amount" value="1"><br>
  19. Currency: <input type="text" name="currency" value="USD"><br>
  20. net_account: <input type="text" name="net_account" value="12 digit number"><br>
  21. secure_id: <input type="text" name="secure_id" value="326415"><br>
  22. <div><hr></div>
  23. MI: <input type="hidden" name="merchant_id" value="08762"><br>
  24. MK: <input type="hidden" name="merch_key" value="client_id:client_key"><br>
  25. MTID: <input type="hidden" name="merch_transid" value="<?php echo time(); ?>"><br>
  26. MN: <input type="hidden" name="merch_name" value="Company Ltd"><br>
  27. MA: <input type="hidden" name="merch_account" value="Comany Ltd"><br>
  28. <input type="submit" name="button" value="Make transfer">
  29. </form>
  30. </body>
  31. </html>
  32. <?php
  33. if (isset($_POST['button'])) {
  34. $fields = array(
  35. 'version' => $_POST['version'],
  36. 'amount' => urlencode($_POST['amount']),
  37. 'currency' => $_POST['currency'],
  38. 'net_account' => urlencode($_POST['net_account']),
  39. 'secure_id' => urlencode($_POST['secure_id']),
  40. 'merchant_id' => urlencode($_POST['merchant_id']),
  41. 'merch_key' => urlencode($_POST['merch_key']),
  42. 'merch_transid' => urlencode($_POST['merch_transid']),
  43. 'button' => 'Make Transfer'
  44. );
  45.  
  46. $merchantkey = $_POST['merch_key'];
  47. $amount_value = $_POST['amount']*100;
  48. $ch = curl_init();
  49. curl_setopt($ch, CURLOPT_POST, 1);
  50. curl_setopt($ch, CURLOPT_URL, "https://api.neteller.com/v1/oauth2/token?grant_type=client_credentials");
  51. curl_setopt($ch, CURLOPT_USERPWD, $merchantkey);
  52. curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json", "Cache-Control:no-cache"));
  53. curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  54. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  55. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  56. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  57. $serverOutput = curl_exec($ch);
  58. $serverOutput = json_decode($serverOutput);
  59. if (isset($serverOutput->error) && $serverOutput->error != '') {
  60. header("Location:your_page.php?status=" . $serverOutput->error->message . "&payment_type=neteller");
  61. exit;
  62. }
  63. if (isset($serverOutput->accessToken) && $serverOutput->accessToken != "") {
  64. $access_token = $serverOutput->accessToken;
  65. $requestParams = array(
  66. "paymentMethod" => array(
  67. "type" => "neteller",
  68. "value" => $_SESSION["email"],
  69. ),
  70. "transaction" => array (
  71. "merchantRefId" => (string) time(),
  72. "amount" => $amount_value,
  73. "currency" => "USD"
  74. ),
  75. "verificationCode" => $_POST['secure_id']
  76. );
  77. $curl = curl_init();
  78. curl_setopt($curl, CURLOPT_POST, 1);
  79. curl_setopt($curl, CURLOPT_URL, "https://api.neteller.com/v1/transferIn");
  80. curl_setopt($curl, CURLOPT_HTTPHEADER,
  81. array("Content-Type:application/json", "Authorization: Bearer $access_token"));
  82. curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($requestParams));
  83. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  84. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  85. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  86. $serverOutput = curl_exec($curl);
  87. $serverOutput = json_decode($serverOutput);
  88. if (isset($serverOutput->error->code) && $serverOutput->error->message != '') {
  89. header("Location:payment.php?status=" . urlencode($serverOutput->error->message) . "
  90. &payment_type=neteller");
  91. exit;
  92. }
  93. curl_close($ch);
  94. //Success full return array;
  95. echo "<pre>";
  96. print_r($serverOutput);
  97. }
  98. }
  99. ?>

Saturday, 30 May 2015

Datatables ajax bootstrap pagination with codeigniter

If you want to implement datatables with ajax using codeigniter and you can also use code if you are using core php stuff in your application.

1. You need to include required jQuery for datatables , ajax processing.
  1. <script src="<?php echo base_url(); ?>assets/js/jquery-1.11.0.min.js"></script>
  2. <script src="<?php echo base_url(); ?>assets/js/jquery.dataTables.min.js"></script>
  3. <script src="<?php echo base_url(); ?>assets/js/dataTables.bootstrap.js"></script>
  4. <script src="<?php echo base_url(); ?>assets/js/datatables/responsive/js/datatables.responsive.js">
  5. </script>
  6. <script src="<?php echo base_url(); ?>assets/js/datatables/jquery.dataTables.columnFilter.js">
  7. </script>
2. Your html source file or you can say your view file will goes like below.
  1. <div class="main-content">
  2. <div class="row"><h2>Brokers Listing</h2>
  3. <div class="panel panel-primary" data-collapsed="0">
  4. <div class="panel-body">
  5. <table class="table table-bordered table-striped datatable" id="broker_listing">
  6. <thead><tr>
  7. <th class="no-sort">#</th>
  8. <th>Broker Name</th>
  9. <th>Email</th>
  10. <th>Created Date</th>
  11. <th>Status</th>
  12. <th class="no-sort">Actions</th>
  13. </tr></thead><tbody></tbody>
  14. </table>
  15. </div>
  16. </div>
  1. <script type="text/javascript">
  2. jQuery(window).load(function(){
  3. var $ = jQuery;
  4. $("#broker_listing").dataTable({
  5. "bProcessing": true,
  6. "bServerSide": true,
  7. "sAjaxSource": baseurl+'broker/get_broker_listing',
  8. "sPaginationType": "bootstrap",
  9. "columnDefs": [ {
  10. "targets": 'no-sort',
  11. "orderable": false,
  12. }],
  13. "fnRowCallback": function(nRow, aData, iDisplayIndex) {
  14. nRow.setAttribute('id',"tr_"+aData[0]);
  15. }
  16. });
  17. });
  18. $(function() {
  19. $(document).on('click', '.removeRcords', function(event) {
  20. event.preventDefault();
  21. var idss=$(this).attr('id');
  22. var rid=idss.split("_")[1];
  23. do_remove_ajax('broker_remove',rid);
  24. });
  25. });
  26. </script>
3. Your controller function will go like below
  1. public function get_broker_listing() {
  2. $this->load->model('common');
  3. $aColumns = array('broker_id' ,'name', 'email', 'created_date', 'status');
  4. $sIndexColumn = "broker_id";
  5. $sTable = "cbf_broker_registration";
  6. $iDisplayStart=$this->input->get('iDisplayStart',true);
  7. $iDisplayLength=$this->input->get('iDisplayLength',true);
  8. $iSortCol_0=$this->input->get('iSortCol_0',true);
  9. $iSortingCols=$this->input->get('iSortingCols',true);
  10. $sLimit = "";
  11. if ( isset($iDisplayStart) && $iDisplayLength != '-1' )
  12. {
  13. $sLimit = "LIMIT ". $iDisplayStart.", ".$iDisplayLength;
  14. }
  15. if ( isset($iSortCol_0))
  16. {
  17. $sOrder = "ORDER BY ";
  18. for($i=0 ; $i<intval( $iSortingCols ) ; $i++ ){
  19. if($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
  20. {
  21. $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
  22. ".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
  23. }
  24. }
  25. $sOrder = substr_replace( $sOrder, "", -2 );
  26. if( $sOrder == "ORDER BY" ){
  27. $sOrder = "";
  28. }
  29. }
  30. $sSearch=$this->input->get('sSearch',true);
  31. $sWhere = "";
  32. if ( $sSearch != "" ){
  33. $sWhere = "WHERE (";
  34. for ( $i=0 ; $i<count($aColumns) ; $i++ ){
  35. $sWhere .= $aColumns[$i]." LIKE '%".$sSearch."%' OR ";
  36. }
  37. $sWhere = substr_replace( $sWhere, "", -3 );
  38. $sWhere .= ')';
  39. }
  40. /* Individual column filtering */
  41. for($i=0 ; $i<count($aColumns) ; $i++){
  42. if($_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != ''){
  43. if($sWhere == ""){
  44. $sWhere = "WHERE ";
  45. }else{
  46. $sWhere .= " AND ";
  47. }
  48. $sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%'";
  49. }
  50. }
  51. $sEcho=$_GET['sEcho'];
  52. $result=$this->common->broker_listing($sTable, $sWhere, $sOrder, $sLimit, $aColumns,$sIndexColumn,
  53. $sEcho);
  54. echo json_encode($result);
  55. }
4. Your model function will goes like below. you can also give edit and remove functionality for that just returning Edit Link and class " removeRcords ". you can put other links as your requirement.
  1. function broker_listing($sTable, $sWhere, $sOrder, $sLimit, $aColumns,$sIndexColumn,$sEcho) {
  2. $sQuery = "SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
  3. FROM $sTable $sWhere $sOrder $sLimit";
  4. $rResult = $this->db->query($sQuery);
  5. $rResult_array=$rResult->result_array();
  6. $iFilteredTotal = count($rResult_array);
  7. /* Total data set length */
  8. $sQuery_TR = "SELECT COUNT(".$sIndexColumn.") AS TotalRecords FROM $sTable";
  9. $rResult_TR = $this->db->query($sQuery_TR);
  10. $rResult_array_TR=$rResult_TR->result_array();
  11. $iTotal = $rResult_array_TR[0]['TotalRecords'];
  12. $output = array("sEcho" => intval($sEcho),"iTotalRecords" => intval($iTotal),
  13. "iTotalDisplayRecords" => intval($iTotal), //$iFilteredTotal,
  14. "aaData" => array()
  15. );
  16. foreach($rResult_array as $aRow){
  17. $row = array();
  18. foreach($aColumns as $col){
  19. if($aRow[$col]=='D'){
  20. $row[] = 'Disable';
  21. }else{
  22. $row[] = $aRow[$col];
  23. }
  24. }
  25. array_push($row, '<a href="'.base_url().'admin/broker/edit_broker/'.$aRow['broker_id'].'"
  26. class="editRcords btn btn-default btn-sm btn-icon icon-left"><i class="entypo-pencil"></i>
  27. Edit</a> <a href="javascript:void(0)" id="brkr_'.$aRow['broker_id'].'"
  28. class="removeRcords btn btn-danger btn-sm btn-icon icon-left">
  29. <i class="entypo-cancel"></i> Remove</a>');
  30. $output['aaData'][] = $row;
  31. }
  32. return $output;
  33. }
5. You can setup jQuery function through out your project OR Application. you have to pass two param action_key and id for removing records.
  1. function do_remove_ajax(action_key,id){
  2. $.ajax({
  3. url baseurl+'controller/do_remove',
  4. type 'POST',
  5. data{idid,action_keyaction_key},
  6. dataType 'json',
  7. beforeSend function() {
  8. },
  9. complete function() {
  10. },
  11. success function(response) {
  12. switch (response.Mstatus) {
  13. case 'success'
  14. $("#"+response.process_id).hide();
  15. break;
  16. case 'error'
  17. showalert(response.msg,'showmessage_jscbf');
  18. break;
  19. default
  20. break;
  21. }
  22. }
  23. });
  24. }
6. Your view load function will goes like below
  1. public function view_broker() {
  2. $data['meta_title'] = 'Broker Listing';
  3. $data['meta_keywords'] = 'Broker Listing';
  4. $data['meta_desc'] = 'Broker Listing';
  5. $data['sidebarmenu'] = 'sidebar_menu';
  6. $data['top_menu'] = 'top_menu';
  7. $data['main'] = 'broker_listing';
  8. $data['footer'] = 'footer';
  9. $this->load->vars($data);
  10. $this->load->view($this->admin_dashboard);
  11. }
NOTE: Flow goes like below sidebar menu link click--->view_broker() function call---> call ajax function get_broker_listing() ---> call model function broker_listing--->controller return json formate required for datatables.

Thursday, 14 May 2015

Creating store procedure Mysql Insert

Showing you some examples of creating store procedure in mysql.
1. "At The Rate" sign used for local variable declare.
2. For calling a store procedure use function below. i am using Codeigniter.
  1. public function AddBooking(){
  2. $sql="call usp_AddBooking()";
  3. $parameters=array();
  4. $query = $this->db->query($sql,$parameters);
  5. return $query->result();
  6. }
  7. DROP PROCEDURE IF EXISTS `usp_AddBooking` $$
  8. CREATE PROCEDURE `usp_AddBooking`(
  9. IN iVendorId INT,
  10. IN iCustomerId INT,
  11. IN iServiceId INT,
  12. IN dServiceBookingTime DATETIME,
  13. IN dArrivalTime DATETIME
  14. )
  15. BEGIN
  16. DECLARE iBookingId INT default 0;
  17. BEGIN
  18. -- ERROR
  19. set ErrorCode = -999;
  20. rollback;
  21. END;
  22. DECLARE exit handler for sqlwarning
  23. BEGIN
  24. -- WARNING
  25. set ErrorCode = -888;
  26. rollback;
  27. END;
  28. START TRANSACTION;
  29. INSERT INTO skin_booking
  30. (iVendorId
  31. ,iCustomerId
  32. ,iServiceId
  33. ,dServiceBookingTime
  34. ,dArrivalTime
  35. ,eStatus
  36. ,dCreatedDate
  37. ,iBookingId
  38. )
  39. VALUES
  40. (iVendorId
  41. ,iCustomerId
  42. ,iServiceId
  43. ,dServiceBookingTime
  44. ,dArrivalTime
  45. ,'1'
  46. ,NOW()
  47. ,iBookingId
  48. );
  49. SET @iBookingId = LAST_INSERT_ID();
  50. SELECT @iBookingId as BookingId;
  51. COMMIT;
  52. END$$

Register users and login through store procedure mysql

1. Signup a user through store procedure.
2. "mysecret" here you can use your key. password will be encrypted using AES
3. You can call store procedure like below
  1. CALL`AddCustomerDetails`('David Warnor','david@gmail.com','12','male','2377.34','34343.343');
  2. CREATE PROCEDURE `AddCustomerDetails`(
  3. IN `vCustomerName` VARCHAR(50),
  4. IN `vEmail` VARCHAR(50),
  5. IN `vPassword` VARCHAR(50),
  6. IN `eGender` VARCHAR(10),
  7. IN `dLatitude` FLOAT,
  8. IN `dLongitude` FLOAT
  9. )
  10. BEGIN
  11. DECLARE ResultCount INT default 0;
  12. DECLARE skey VARCHAR(15) default 'mysecret';
  13. DECLARE eStatus INT default 1;
  14. DECLARE iCustomerId INT;
  15.  
  16. SET @ResultCount = (SELECT COUNT(iCustomerId) FROM table_name WHERE vEmail = vEmail);
  17. IF (@ResultCount > 0) THEN
  18. SET @iCustomerId = 0;
  19. SELECT @iCustomerId;
  20. ELSE
  21. INSERT INTO table_name
  22. (vCustomerName
  23. ,vEmail
  24. ,vPassword
  25. ,eGender
  26. ,dLatitude
  27. ,dLongitude
  28. ,eStatus
  29. ,dCreatedDate
  30. )
  31. VALUES
  32. (vCustomerName
  33. ,vEmail
  34. ,AES_ENCRYPT(vPassword,skey)
  35. ,eGender
  36. ,dLatitude
  37. ,dLongitude
  38. ,eStatus
  39. ,NOW()
  40. );
  41. SET @iCustomerId = LAST_INSERT_ID();
  42. SELECT @iCustomerId as CustomerId;
  43. END IF;
  44. END
1. Now above will add a entry to your mysql table let create a store procedure which will validate and check credentials.
  1. ALL `CheckLogin`('david@gmail.com', '123123', '0');
  2. CREATE PROCEDURE `CheckLogin`(
  3. IN `Email` VARCHAR(255),
  4. IN `Psw` VARCHAR(255),
  5. IN `UserType` INT(11)
  6. )
  7. BEGIN
  8. DECLARE ResultCount INT;
  9. DECLARE ResultMessage varchar(15);
  10. DECLARE skey VARCHAR(15) default 'secrets';
  11. IF (UserType = 0) THEN
  12. SET @ResultCount = (SELECT COUNT(C.iCustomerId) FROM customerdetails C
  13. WHERE C.vEmail = Email AND C.vPassword = AES_ENCRYPT(Psw,skey) AND C.eStatus = 1);
  14. IF (@ResultCount > 0) THEN #For Customer
  15. SELECT * from customerdetails C WHERE C.vEmail = Email AND C.vPassword = AES_ENCRYPT(Psw,skey)
  16. AND C.eStatus = 1;
  17. ELSE
  18. SET @ResultMessage='User not found.';
  19. SELECT @ResultMessage;
  20. END IF;
  21. ELSE
  22. SET @ResultCount = (SELECT COUNT(V.iVendorId) FROM vendor V WHERE V.vEmail = Email
  23. AND V.vPassword = AES_ENCRYPT(Psw,skey) AND V.eStatus = 1);
  24. IF (@ResultCount > 0) THEN
  25. SELECT * from vendor V WHERE V.vEmail = Email AND V.vPassword = AES_ENCRYPT(Psw,skey)
  26. AND V.eStatus = 1;
  27. ELSE
  28. SET @ResultMessage='vendor not found.';
  29. SELECT @ResultMessage;
  30. END IF;
  31. END IF;
  32. END

Monday, 11 May 2015

Ajax captcha using codeigniter php bootstrapvalidator

I will show you how you can create a captcha validation with Codeiginter based on Ajax.
1. Below is my model name as Mcaptcha
  1. class Mcaptcha extends CI_Model {
  2. protected $ci;
  3. function __construct() {
  4. // Call the Model constructor
  5. parent::__construct();
  6. $this->ci =& get_instance();
  7. }
  8. function setCaptcha(){
  9. $this->load->helper('captcha');
  10. $rand = substr(md5(microtime()),rand(0,26),5);
  11. $vals = array(
  12. 'img_path' => FCPATH.'assets/captcha/',
  13. 'img_url' => base_url().'assets/captcha/',
  14. 'expiration' => 1800,// half hour
  15. 'font_path' => FCPATH.'assets/fonts/Cabin-BoldItalic.ttf',
  16. 'img_width' => '140',
  17. 'img_height' => 30,
  18. 'word' => $rand,
  19. );
  20. $cap = create_captcha($vals);
  21. $this->ci->session->set_userdata(array('cpt'=>$rand, 'img' => $cap['time'].'.jpg'));
  22. return $cap['image'] ;
  23. }
  24. }
2. Your controller function will goes like below
  1. public function send_us_email() {
  2. $this->load->library('form_validation');
  3. $this->load->model('mcaptcha');
  4. $this->form_validation->set_error_delimiters('<span>', '</span>');
  5. $this->form_validation->set_rules('sname', 'Name', 'trim|required|max_length[20]|xss_clean');
  6. $this->form_validation->set_rules('captcha', 'Captcha', 'trim|required|max_length[5]|
  7. callback_validate_captcha|xss_clean');
  8. if ($this->form_validation->run() == FALSE){
  9. // if any fields on form not validated properly we need to unset session and unlink captcha
  10. image previously created and then regenerate captcha and passing it to Cmessage.
  11. if(file_exists(FCPATH."assets/captcha/".$this->session->userdata['img']))
  12. unlink(FCPATH."assets/captcha/".$this->session->userdata['img']);
  13. $this->session->unset_userdata('cpt');
  14. $this->session->unset_userdata('img');
  15. $captcha = $this->mcaptcha->setCaptcha();
  16. echo json_encode(array('Mstatus'=>'error','Cmessage'=>$captcha,'msg' => validation_errors()));
  17. }else{
  18. $sname=set_value('sname');
  19. $captcha=set_value('captcha');
  20. $data=array('name'=>$sname);
  21. $send_us_a_email_template= $this->load->view('email_templates/send_us_a_email', $data, true);
  22. $this->email->from('youremail@domain.com',"YourTITLE");
  23. $this->email->to($semail);
  24. $this->email->subject('Customer Query Request');
  25. $this->email->message($send_us_a_email_template);
  26. if ($this->email->send()){
  27. // same logic above if every thing goes well.
  28. if(file_exists(FCPATH."assets/captcha/".$this->session->userdata['img']))
  29. unlink(FCPATH."assets/captcha/".$this->session->userdata['img']);
  30. $this->session->unset_userdata('cpt');
  31. $this->session->unset_userdata('img');
  32. echo json_encode(array('Mstatus'=>'success','Cmessage'=>'We have recieved
  33. your email and we will get back to you shortly. Thanks.','msg'=>''));
  34. }else{
  35. echo json_encode(array('Mstatus'=>'error','Cmessage'=>'','msg' => 'Error
  36. in processing your query. Please try later.'));
  37. }
  38. }
  39. }
3. Below is call back function to validate captcha enter by user.
  1. public function validate_captcha($str){
  2. if($str != $this->session->userdata['cpt']){
  3. $this->form_validation->set_message('validate_captcha', 'Wrong captcha code,
  4. hmm are you the Terminator?');
  5. return false;
  6. }else{
  7. return true;
  8. }
  9. }
4. Your jQuery goes like below
  1. $(document).ready(function() {
  2. $('#submit-link-form').bootstrapValidator({
  3. message: 'This value is not valid',
  4. feedbackIcons: {
  5. valid: 'glyphicon glyphicon-ok',
  6. invalid: 'glyphicon glyphicon-remove',
  7. validating: 'glyphicon glyphicon-refresh'
  8. },
  9. fields: {
  10. linkname: {
  11. validators: {
  12. notEmpty: {
  13. message: 'The name is required.'
  14. },
  15. stringLength: {
  16. min: 4,
  17. message: 'Name must be 4 characters long.'
  18. }
  19. }
  20. },
  21. scaptcha: {
  22. validators: {
  23. notEmpty: {
  24. message: 'Captcha verification is required.'
  25. }
  26. }
  27. }
  28. }
  29. })
  30. .on('success.form.bv', function(e) {
  31. e.preventDefault();
  32. var $form = $(e.target);
  33. var bv = $form.data('bootstrapValidator');
  34. $.ajax({
  35. url: $form.attr('action')+'?time='+timestamp,
  36. type: $form.attr('method'),
  37. data: $form.serialize(),
  38. dataType:'json',
  39. beforeSend: function() {
  40. },
  41. complete: function() {
  42. },
  43. success: function(response){
  44. switch(response.Mstatus){
  45. case 'success':
  46. break;
  47. case 'error':
  48. break;
  49. default:
  50. break;
  51. }
  52. }
  53. });
  54. });
  55. });
5. Your bootstrap model popup will looks like below
  1. <div class="container">
  2. <div class="modal fade animate1 faster-modal" id="send-us-email-modal" tabindex="-1" role="dialog"
  3. aria-labelledby="sendusemailLabel" aria-hidden="true">
  4. <div class="modal-dialog">
  5. <div class="modal-content">
  6. <div class="modal-header">
  7. <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span>
  8. <span class="sr-only">Close</span></button>
  9. <h4 class="modal-title" id="sendusemailLabel">Send Us Email</h4>
  10. </div>
  11. <div class="modal-body">
  12. <?php echo form_open(base_url().'root/send_us_email',array('id' =>'send-us-email-form',
  13. 'name' =>'send-us-email-form','method'=>'post'));?>
  14. <div class="faster-ajax-loader faster_ajax_loader" style="display:none;"></div>
  15. <aside class="form-group">
  16. <div class="popup_message"></div>
  17. </aside>
  18. <aside class="form-group">
  19. <input type="text" class="form-control required" placeholder="Your Name" name="sname" id="sname" />
  20. </aside>
  21. <aside class="form-group form-capcha"> <span class="generated-capcha"><img
  22. src="<?php echo base_url();?>images/default.jpg" width="140" height="30" alt="Verification Code">
  23. </span><a href="javascript:void(0);" title="Refresh Verification Code">
  24. <span class="glyphicon glyphicon-refresh refresh-regenerate"></span></a> </aside>
  25. <aside class="form-group">
  26. <input class="form-control text required" id="captcha" type="text" name="captcha" value=""
  27. placeholder="Verification Code" />
  28. </aside>
  29. <aside class="form-group">
  30. <input type="submit" class="btn-features animate1" value="Send Us Email" />
  31. </aside>
  32. </form>
  33. </div>
  34. </div>
  35. </div>
  36. </div>
  37. </div>
6. If you would like to refresh captcha if it is not visible properly to users then refresh captcha on Link / Image click .Your js code will goes like below
  1. $(function(){
  2. $(document).on('click', '.refresh-regenerate', function(){
  3. var myformclick=$(this).closest('form').attr('id');
  4. $.ajax({
  5. url: baseurl+"root/generate_captcha",
  6. type: "POST",
  7. data: "cap=1",
  8. cache: false,
  9. dataType:'json',
  10. beforeSend: function() {
  11. $("#"+myformclick).find(".faster_ajax_loader").css('display','block');
  12. },
  13. complete: function() {
  14. $("#"+myformclick).find(".faster_ajax_loader").css('display','none');
  15. },
  16. success: function(response){
  17. $("#"+myformclick).find(".generated-capcha").html(response.Cmessage);
  18. }
  19. });
  20. });
  21. });
7. I am calling generate_captcha function so that on each click new captcha image will be generated.
  1. public function generate_captcha(){
  2. if(file_exists(FCPATH."assets/captcha/".$this->session->userdata['img']))
  3. unlink(FCPATH."assets/captcha/".$this->session->userdata['img']);
  4. $this->load->model('mcaptcha');
  5. $this->session->unset_userdata('cpt');
  6. $this->session->unset_userdata('img');
  7. $captcha = $this->mcaptcha->setCaptcha();
  8. echo json_encode(array('Mstatus'=>'success','Cmessage'=>$captcha,'msg' => validation_errors()));
  9. }

Creating subdomain on amazon ubuntu Ec2

1. Create a directory from command line
  1. sudo touch /var/www/your-directory
2. Create a conf file on location /etc/apache2/site-available/
  1. i. sudo touch /etc/apache2/site-available/your-directory-name.domainname.com.conf
  2. ii. Just copy 000-default.config data to newly created file above
  3. sudo cp /etc/apache2/site-available/000-default.conf
  4. /etc/apache2/site-available/your-directory-name.domainname.com.conf
  5. iii. open file for edit
  6. sudo nano /etc/apache2/site-available/your-directory-name.domainname.com.conf
  7. and replace
  8.  
  9. DocumentRoot /var/www/your-directory-name
  10.  
  11. iv. sudo service apache2 reload.
  12. v. sudo service apache2 restart.
3. After above process go to amazon hosted zone just follow below steps
  1. 1. create a records set put name of your choice in name required fields
  2. 2. put www.yourdomain.com. in value and save records set.

Minify your javascript files offline with uglifyjs

You can compress or minify your Javascript / jQuery code by visiting to resources which is available but if you want to use it on your localhost so you can use it and run like below on windows.
  1. 1. Installed Node.js
  2. 2. Set envirnment variable
  3. NODE_PATH
  4. C:\Program Files\nodejs\UglifyJS\bin\uglify;C:\Program Files\nodejs\node.exe;
  5. 3. Download uglify master from gits and put in folder
  6. C:\Program Files\nodejs\uglifyjs
  7. 4. run command
  8. Run npm -g install uglify-js
  9. final if you want to minify js
  10. 5. Run uglifyjs -o app.min.js app.js
Note: app.min.js is your name and app.js is your source js which you want to compress OR minify.

Tomcat 8.0.21 running in ubuntu 14.04 TLS

I am explaining every step to run tomcat in ubuntu 8.0.21 and how to setup your projects and running Servlets ,Jsp.
1. Install JDK 7 before installing tomcat.
  1. sudo apt-get install openjdk-7-jdk
2. Download the latest version of tomcat tomcat.apache.org , i downloaded Apache Tomcat 8.0.21
  1. I rename dowonload folder to "apache-tomcat"
  2. and move it to location /usr/local/apache-tomcat
  3. go to /usr/local/apache-tomcat/conf/tomcat-users.xml
  4. or you can edit from terminal sudo nano /usr/local/apache-tomcat/conf/tomcat-users.xml
  5. place below lines & save. [ctrl+^+x then press Y]
  6. <role rolename="manager-gui">
  7. <role rolename="admin-gui">
  8. <user password="rohit" roles="manager-gui,admin-gui" username="rohit">
  9. </user>
  10. </role>
  11. </role>
3. We have to create a bash file for running and stoping tomcat. Create a new file tomcat8021 in /etc/init.d/ and add the below code
  1. #!/bin/bash
  2. export CATALINA_HOME=/usr/local/apache-tomcat
  3. PATH=/sbin:/bin:/usr/sbin:/usr/bin
  4. start() {
  5. sh $CATALINA_HOME/bin/startup.sh
  6. }
  7. stop() {
  8. sh $CATALINA_HOME/bin/shutdown.sh
  9. }
  10. case $1 in
  11. start|stop) $1;;
  12. restart) stop; start;;
  13. *) echo "Run as $0 "; exit 1;;
  14. esac
4. Give 755 permission
  1. sudo chmod 755 /etc/init.d/tomcat8021
5. For starting stoping tomcat
  1. sudo /etc/init.d/tomcat8021 start / stop
6. We need to set Classpath and java home varibale to work properly. so i edited the file call environment place below lines there.
  1. sudo nano /etc/environment
  2. CLASSPATH=.:/usr/lib/jvm/default-java/bin:/usr/local/apache-tomcat/lib/servlet-api.jar
  3. JAVA_HOME=/usr/lib/jvm/default-java

Creating a new project in ubuntu 14.04 TLS

1. I created a folder called store in /usr/local/apache-tomcat/
2. store(Project Folder) ---> WEB-INF ---> classes(DIR) , lib(DIR) , web.xml (file)
3. web.xml file looks like below
  1. <web-app>
  2. <servlet>
  3. <servlet-name>HelloWorld</servlet-name>
  4. <servlet-class>HelloWorld</servlet-class>
  5. </servlet>
  6. <servlet-mapping>
  7. <servlet-name>HelloWorld</servlet-name>
  8. <url-pattern>/HelloWorld</url-pattern>
  9. </servlet-mapping>
  10. </web-app>
4. Inside classes folder your source file HelloWorld.java will be store for compiling it use below command
  1. mangel@mangel-desktop:/usr/local/apache-tomcat/webapps/store/WEB-INF/classes$
  2. javac -classpath /usr/local/apache-tomcat/lib/servlet-api.jar HelloWorld.java
5. After compile .class file created by above command , then you need to create a context file ,
  1. Go to cd /usr/local/apache-tomcat/conf/Catalina/localhost/ from terminal.
  2. sudo nano store.xml (store is the name of your project folder).
  3. Just paste below line
  4. <!-- Store Context -->
  5. <context debug="0" docbase="store" path="/store" reloadable="true">
  6. </context>
So above all configure manually. just open locahost:8080/store/HelloWord.

Creating subdomain on Digital Ocean

Directory
  1. html refers to main site.
  2. demo , blog outside html (folder) refers to subdomain.
1. Create a directory from command line
  1. sudo touch /var/www/your-directory
2. Create a conf file on location /etc/apache2/site-available/
  1. sudo touch /etc/apache2/sites-available/your-directory-name.domainname.com.conf
  2. Just copy 000-default.config data to newly created file above by below command
  3. sudo cp /etc/apache2/sites-available/000-default.conf
  4. /etc/apache2/site-available/your-directory-name.domainname.com.conf
  5. open file for edit
  6. sudo nano /etc/apache2/sites-available/your-directory-name.domainname.com.conf
  7. and replace
  8. DocumentRoot /var/www/your-directory-name
  9. sudo service apache2 reload.
  10. sudo service apache2 restart.
3. After above proceee go to amazon hosted zone just follow below steps.
  1. Create a records set put name of your choice in name required fields
  2. Put www.yourdomain.com. in value and save records set. it will take 10-15 min to process by amazon.