=======================================================================
How to Download file from local drive
------------------------------***********-------------------------------
public function downloadMe(){
$file = $_GET['sampleFile']; //path to the file on disk
$filename = 'uploads/'.basename($file);
if (file_exists($filename)) {
//set appropriate headers
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
ob_clean();
flush();
//read the file from disk and output the content.
readfile($filename);
exit;
}
}
=======================================================================
How to integrate pagination in CodeIgniter
------------------------------***********-------------------------------
Step1:
Controller Code :-
public function index($limit=0){
$resultset['result_data'] = $this->contacts_model->get_All_contacts_Details(10,$limit);
// pagination code start
$this->load->library('pagination');
$config['base_url']=base_url().'contacts/index/';
$config['total_rows'] = $this->contacts_model->get_count();
$config['per_page'] = 10;
$this->pagination->initialize($config);
$resultset['paging'] = $this->pagination->create_links();
// pagination code end
$resultset['include'] = 'contacts/home';
$this->load->view('userpanel/container',$resultset);
}
Step2:
Model Code :-
public function get_All_contacts_Details($num=20,$start=0){
$this->db->select('*');
$this->db->from('contacts');
$this->db->where('status',1);
$this->db->limit($num,$start);
$query = $this->db->get();
$result = $query->result();
if($query->num_rows() > 0){
return $result;
}else{
return $result;
}
}
========================
public function get_contacts_count() {
$this->db->select('id')->from('contacts')->where('status',1);
$query=$this->db->get();
return $query->num_rows();
}
Step 3:
View Code :-
<div class="pagination">
<ul>
<?php echo $paging; ?>
</ul>
</div>
=======================================================================
How to add Ajax in a page
------------------------------***********-------------------------------
--------*****----------
Normal ajax
--------*****----------
<select onchange="get_code(this.value)">
</select>
<script>
function get_code(value)
{
$.ajax({
type: "POST",
url: "get_code.php",
data: "user_code=" + value,
success: function(result) {
//alert(result);
if (result != "error")
{
document.getElementById('user_name').value = result;
}
}
});
}
</script>
--------*****----------
MVC ajax
--------*****----------
$.ajax({
type: "POST",
url: "<?php echo base_url();?>controller/model",
data: "user_ids="+ids, //OR +'&role_id='+role_id,
success: function(result){
if(result == 'true'){
window.location.href = "<?php echo base_url();?>usergroups";
}
}
});
http://imar.spaanjaars.com/357/a-scrollable-table-with-a-fixed-header
=======================================================================
How to access denied page from direct url
------------------------------***********-------------------------------
$log_data = $this->session->userdata('user_data');
$log=@$log_data['is_logged_in'];
if(@$log==true){
$this->load->view('userpanel/header');
$this->load->view($include);
$this->load->view('userpanel/footer');
} else {
//die("Access denied");
redirect('home');
}
=======================================================================
Edit with unique value
------------------------------***********-------------------------------
public function edit($user_record,$id){
$this->db->select('id')->from('contacts')->where('phone',$user_record['phone'])->where('status',1)->where('id !=',$id);
$query=$this->db->get();
$result = $query->row();
$nub_row = $query->num_rows();
if($nub_row == 0){
$this->db->update("contacts",$user_record,array("id"=>$id));
$status = true;
}else{
$status = false;
}
return $status;
}
=======================================================================
Function Not allow to add space, html5 custom validation and Placeholder
------------------------------***********-------------------------------
<input id="lastname" onblur="checkSpace(this.id);" oninput="setCustomValidity('')" oninvalid="setCustomValidity('Please enter last name')" name="lastname" minlength="2" type="text" value="" placeholder="Please enter valid" required />
<SCRIPT language=Javascript>
//check for space
function checkSpace(myid){
var str = document.getElementById(myid).value;
var value = str.trim();
if (value == ' ') {
document.getElementById(myid).value = '';
} else {
document.getElementById(myid).value = value;
return true;
}
}
</SCRIPT>
=======================================================================
Function accept only number
------------------------------***********-------------------------------
<input onkeypress="return isNumberKey(event)" name="mobile" minlength="10" type="text" value="" required />
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}else{
return true;
}
}
=======================================================================
Function remove spacial character from string
------------------------------***********-------------------------------
function removeSpecialChar($string=0){
$new_string = ereg_replace("[^A-Za-z0-9]", "", $string);
return $new_string;
}
=======================================================================
Function remove whitespaces float value from string
------------------------------***********-------------------------------
<SCRIPT language=Javascript>
function checkFloatSpace(myid){
var str = document.getElementById(myid).value;
var value = str.trim();
if (value == ' ') {
document.getElementById(myid).value = '';
} else {
value = parseFloat(value);
document.getElementById(myid).value = value;
return true;
}
}
</SCRIPT>
=======================================================================
Function disabled right click on browser
------------------------------***********-------------------------------
<body onload="preventBack();" oncontextmenu="return false">
<script>
function disableBackButton()
{
window.history.forward()
}
disableBackButton();
window.onload=disableBackButton();
window.onpageshow=function(evt) { if(evt.persisted) disableBackButton() }
window.onunload=function() { void(0) }
function DisableBack() {
window.history.forward();
}
DisableBack();
window.onload = DisableBack;
window.onpageshow = function(evt) {
if (evt.persisted) DisableBack();
}
window.onunload = function() { void (0); }
function preventBack(){
window.history.forward(1);
}
</script>
=======================================================================
Function prevent cut copy and paste option
------------------------------***********-------------------------------
$(document).ready(function(){
$(document).keydown(function(event) {
if (event.ctrlKey==true && (event.which == '118' || event.which == '86')) {
alert('thou. shalt. not. PASTE!');
event.preventDefault();
}
});
});
=======================================================================
Function check login with case sensitive
------------------------------***********-------------------------------
// SELECT * FROM (`users`) WHERE cast(username as binary)= 'Mytest' AND cast(password as binary)= 'mytest' AND `status` = 1
public function check_login($user,$pass){
$result = null;
$this->db->select("*");
$this->db->from("users");
$this->db->where('cast(username as binary)=',$user);
$this->db->where('cast(password as binary)=',$pass);
$this->db->where('status',1);
$this->db->or_where('account_id',$user);
$query = $this->db->get();
$result = $query->result();
if($query->num_rows() > 0){
return $result;
}else{
return $result;
}
}
=======================================================================
IMP Function BrowserBack button desabled in all browser
------------------------------***********-------------------------------
<script>
window.location.hash="no-back-button";
window.location.hash="Again-no-back-button";//for google chrome
window.onhashchange=function(){window.location.hash="no-back-button";}
</script>
OR
<script>
window.location.hash="##";
window.location.hash="###";//for google chrome
window.onhashchange=function(){window.location.hash="";}
</script>
=======================================================================
Function to Create native Session in a Codeigniter (http://www.moreofless.co.uk/using-native-php-sessions-with-codeigniter/)
------------------------------***********-------------------------------
Step 1:
application/libraries folder, create a new file called Nativesession.php in there. Put the following code into Nativesession.php:
if ( ! defined('BASEPATH') )
exit( 'No direct script access allowed' );
class Nativesession
{
public function __construct()
{
session_start();
}
public function set( $key, $value )
{
$_SESSION[$key] = $value;
}
public function get( $key )
{
return isset( $_SESSION[$key] ) ? $_SESSION[$key] : null;
}
public function regenerateId( $delOld = false )
{
session_regenerate_id( $delOld );
}
public function delete( $key )
{
unset( $_SESSION[$key] );
}
}
Step 2:
Using your new library in a controller
You use your new library in the same way as you do any other CI library:
class Login extends CI_Controller
{
public function index()
{
//load our Nativesession library
$this->load->library( 'nativesession' );
//Read the username from session
$username = $this->nativesession->get( 'username' );
//Update shopping cart session data
$this->nativesession->set( 'cart', $cart );
}
}
=======================================================================
Function add to cart core php functionalty
------------------------------***********-------------------------------
leapscale.co.in
http://www.h2database.com/html/features.html
//test code start
public function addtocart(){
//$this->session->unset_userdata('productdata'); die;
$pid = $_POST['pid'];
$qty = $_POST['qty'];
$cart = $this->session->userdata('cartproduct');
if(is_array($cart) !=''){
$max = count($cart);
$flag = 0;
$productData = array();
for($i=0;$i<$max;$i++){
if($cart[$i]['product_id'] == $pid){
$flag = 1;
}
if($cart[$i]['product_id'] != '' && $cart[$i]['quantity'] !='')
{
$productData[] = array(
'product_id'=>$cart[$i]['product_id'],
'quantity'=>$cart[$i]['quantity']
);
}
}
if($flag == 0)
{
$productData[] = array(
'product_id'=>$pid,
'quantity'=>$qty
);
$cartData = $productData;
$this->session->set_userdata('cartproduct',$cartData);
}
}else{
$productData = array(
'product_id'=>$pid,
'quantity'=>$qty
);
$cartData[0] = $productData;
$this->session->set_userdata('cartproduct',$cartData);
}
print_r($this->session->userdata('cartproduct'));
exit;
}
=======================================================================
Function to validate radio buttons
------------------------------***********-------------------------------
STEP 1:
<tbody>
<tr>
<td>
<input type="radio" name="child_root" id="child_root_A" value="A">
<label for="child_root_A">A</label>
</td>
<td>
<input type="radio" name="child_root" id="child_root_B" value="B">
<label for="child_root_B">B</label>
</td>
<td>
<input type="radio" name="child_root" id="child_root_C" value="C">
<label for="child_root_C">C</label>
</td>
</tr>
</tbody>
STEP 2:
<script>
function get_select()
{
var child_id = get_radio_value("child_root");
if(cat_id == false){
alert('Please check the child.');
return false;
}
}
STEP 3:
function get_radio_value(opt) {
var get_rdo = document.getElementsByName(opt);
var status = false;
for (var i = 0; i < get_rdo.length; i++) {
if (get_rdo[i].checked) {
return status = true;
}
}
return status;
}
STEP 4: validate complete
=======================================================================
Function use code-igniter library helper function
------------------------------***********-------------------------------
STEP 1:
- create a file in a folder called 'my_util_helper.php' => "app\helpers\"
- on your "app\config" => include the name of helper file in =>'autoload.php' this file
Eg. $autoload['helper'] = array('url','file','form','email','my_url_helper','my_email_helper','my_image_helper','my_util_helper');
STEP 2:
-create a function or call data from another module
Eg.
function getCountry($id)
{
$CI =& get_instance();
$CI->load->model('home/home_model');
$r = $CI->home_model->getCountry();
echo "<option value='0'>-Select Country-</option>";
if(count($r))
{
for($i=0;$i<count($r);$i++)
{ ?>
<option value='<?php echo $r[$i]->id?>'
<?php if(isset($id) && $id!='' && $id==$r[$i]->id){ echo "selected"; } ?>><?php echo $r[$i]->name;?></option>
<?php }
}
}
STEP 3:
- how to use this function any whir => just call the function on your view file
Eg.
<td class="myCSSclass">Country :
<label style="color: red; font-weight: bold;">*</label>
</td>
<td class="bodytextbold">
<select name="country" id="country" style="width:250px;" onchange="get_state(this.value);">
<?php echo getCountry();?>
</select>
<span id="FieldValidator14" style="color:Red;display:none;">Please select country.</span>
</td>
<td></td><td></td>
</tr>
STEP 4: try & see
=====================================================================
Function add data table and dynamic through server pagination
------------------------------***********-------------------------------
STEP 1:
code-igniter controller code
function getContactData(){
if($_GET['draw'] == 1){
$start=0;
$length=10;
}else{
$start = $_GET['start'];
$length = $_GET['length'];
}
$data_array = array();
$log_data = $this->session->userdata('user_data');
$user_id = $log_data['id'];
$this->db->select('*');
$this->db->from('contacts');
$this->db->where('user_id',$user_id);
$this->db->where('status',1);
$this->db->limit($length,$start);
$query = $this->db->get();
$result = $query->result();
$contact_arr = array();
foreach($result as $contact)
{
$chkbox = '';
$actions = 'jj';
$contact_arr[] = array("DT_RowId"=>"row_".$contact->id,'chkbox'=>$chkbox,'first_name'=>$contact->firstname,'last_name'=>$contact->lastname, 'phone'=>$contact->phone, 'action'=>$actions);
}
$data_array['draw'] = $_GET['draw'];
$this->db->select('*')->from('contacts')->where('user_id',$user_id)->where('status',1);
$query1 = $this->db->get();
$result1 = $query1->result();
$data_array['recordsTotal'] = count($result1);
$data_array['recordsFiltered'] = count($result1);
$data_array['data'] = $contact_arr;
echo json_encode($data_array);
exit();
}
STEP 2:
-- Home page which content datatable
-- FIRST => include below link into your pagination
<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.4/css/jquery.dataTables.css">
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
-- SECOND => add below code into your body
<table id="contacts_tbl" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th class="center">Check Box</th>
<th>First Name</th>
<th>Last Name</th>
<th>Number</th>
<th>Actions</th>
</tr>
</thead>
</table>
-- THIRD => add javascript code end of your table
<script type="text/javascript">
var table_object;
$(document).ready(function(){
$('#contacts_tbl').dataTable( {
"processing": true,
"serverSide": true,
"bFilter": false,
"bLengthChange": false,
"ajax": "<?php echo base_url();?>contacts/getContactData",
"columns": [
{ "data": "chkbox" },
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "phone" },
{ "data": "action" }
]
});
});
</script>
=====================================================================
Function upload file using ajax
------------------------------***********-------------------------------
STEP1: Add below html on your page
<form action="#" onsubmit="return upMe();" method="post" enctype="multipart/form-data">
<h3>Upload File using Jquery AJAX in PHP</h3>
<table>
<tr><td>Name:</td><td><input type="text" name="txtname"></td></tr>
<tr><td>File:</td><td><input type="file" name="myfile" id="myfile"></td></tr>
<tr><td> </td><td><input type="submit" value="Upload"></td></tr>
</table>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
<div id="status"></div>
</div>
</form>
STEP2: Add below code on your script
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
function upMe(){
alert();
var formURL = "<?php echo base_url();?>contacts/uploadMe";
var jForm = new FormData();
jForm.append("file", $('#myfile').get(0).files[0]);
$.ajax({
url: formURL,
type: "POST",
data: jForm,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function (data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
return false;
}
</script>
Refrence : http://blog.arvixe.com/using-ajax-to-send-multipart-form/
====================================================================
Function to print page with spacific div
------------------------------***********-------------------------------
<div id=”main-content”> hello page to print </div>
<button onclick="printContent('main-content')">Print Content</button>
<script>
function printContent(el){
var restorepage = document.body.innerHTML;
var printcontent = document.getElementById(el).innerHTML;
document.body.innerHTML = printcontent;
window.print();
document.body.innerHTML = restorepage;
}
</script>
=====================================================================
Image load from any URL source - Image url masking
-----------------------------**********-------------------------------------------------
=====================================================================
Image load from any URL source - Image url masking
-----------------------------**********-------------------------------------------------
$image_url = $_GET['image_url'];
try{
/* $file_list = scandir('../public/assets/img/my_img'); //scandir reads the directory content
$imge_list = [];
foreach($file_list as $key => $value) {
if(!in_array($value,array(".",".."))){
$file_part = explode('.',$value);
$imge_list[$file_part[0]] = $value;
}
}
if (isset($imge_list[$id])) { */
$filename = $image_url; //'../public/assets/img/my_img/'.$imge_list[$id];
//getimagesize() determine the size of any supported given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag and the correspondent HTTP content type.
$mime = ($mime = getimagesize($filename)) ? $mime['mime'] : $mime;
header('Content-Description: File Transfer'); //https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
header("Content-type: " . $mime);
//"Expires: 0" means that a cache will always treat this entry as stale (i.e. it will need to revalidate it first before returning it to a client).
header('Expires: 0');
//Specifies that a cache must revalidate a cached response after it became stale before using that cached response to satisfy the request
header('Cache-Control: must-revalidate');
//Know how large the file is
//header('Content-Length: ' . filesize($filename));
//Clean (erase) the output buffer
ob_clean();
//Flushes the system write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats
flush();
//It returns the number of bytes read on success, or FALSE and an error on failure.
readfile($filename);
/* } else {
echo 'Image not found';
} */
} catch(Exception $e){
echo 'Invalid data';
}