Showing posts with label Php. Show all posts
Showing posts with label Php. Show all posts

Friday 20 May 2022

DataTables warning: table id=example - Invalid JSON response: How to Debug?

  1. Use CTRL+SHIFT+I (or navigate to Current Page Control > Developer > Developer Tools. In the newer versions of Chrome, click the Wrench icon > Tools > Developer Tools.) to enable the Developer Tools.
  2. From within the developer tools click on the Network button. 
  3. Click the "XHR" sub-button.
  4. Initiate an AJAX call.
  5. Double click the Name of the page under the Network button. It will open a new page with the details of the error. 

Wednesday 11 May 2022

Prevent caching data from database in PhP FullCalendar

 <script>
document.addEventListener('DOMContentLoaded', function() {     
        var calendarEl = document.getElementById('calendar');
        var events = [];
        var eventsCache = {};
        var calendar = new FullCalendar.Calendar(calendarEl, {       
        headerToolbar: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
      },     
          eventSources: [{
            cache: false,
              url: 'loadevent.php',
              type: 'POST',
              extraParams: function() {        //  Prevent caching data from database in fullcalendar
                  return {
                    cachebuster: new Date().valueOf()
                  };
                },             
          }],     
    });       
        calendar.render();
        calendar.refetchEvents();       
});   
</script>

Friday 6 May 2022

How to configure PHP Calendar with events from database?

Download fullcalendar  file  from : https://github.com/fullcalendar/fullcalendar/releases

PhP Page

Inside <HEAD> Tag

<link href='fullcalendar-5.10.2/lib/main.min.css' rel='stylesheet' /> // GIVE EXACT FILE PATH   main.min.css, main.min.js
<script src='fullcalendar-5.10.2/lib/main.min.js'></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
        var calendarEl = document.getElementById('calendar');       
        var calendar = new FullCalendar.Calendar(calendarEl, {     
        headerToolbar: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
      },  
      events: 'loadevent.php',
        },             
            displayEventTime: false,
            selectHelper:true,
            weekNumbers: true,
            navLinks: true, // can click day/week names to navigate views
            nowIndicator: true,
            weekNumbers: true,
            dayMaxEventRows: true, // for all non-TimeGrid views
              views: {
                timeGrid: {
                  dayMaxEventRows: 6 // adjust to 6 only for timeGridWeek/timeGridDay
                }
              },         
    });
          calendar.render();
});   
    </script>

Inside BODY Tag

<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 align="center" style=" padding: 3%;"> Calendar Heading</h1>  
<div id='calendar'></div>
</div>
</div>
</div>
</body>

loadevent.php

--> Database connection establishment

$data = array();
$stmt = $con->prepare(" SQL QUERY  ");
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $data[] = array(
        'id'   => $row["No"],
        'title'   => $row["title"],                                                                            // DB ATTRIBUTE NAME FOR TITLE
        'start'   => $row["DATE1"],                                                                     // DB START DATE ENTRY in yy-mm-dd 00:00:00 format
        'end'   => $row["DATE2"],                                                                     // DB END DATE ENTRY in yy-mm-dd 00:00:00 format
        'description' =>   $row[" Description "],    // DB Description attribute
      
    );
    //result is in row
}

echo json_encode($data);

Tuesday 3 May 2022

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

Reason for the error:
You are mixing mysqli and mysql extensions in the code, which will not work. mysqli has many improvements over the original mysql extension, so it is recommended to use mysqli .

Friday 29 April 2022

Pre Populate jquery Token input textbox with PhP MySQLi Resultset

Tokeninput is a jQuery plugin that allows users to select multiple items from a predefined list. 
  • Download jquery token input plugin from https://loopj.com/jquery-tokeninput/
  • Extract the zip file and put jquery.tokeninput.js and token-input.css in the application root folder.
  • Download the latest version of jquery.min.js
SQL

CREATE TABLE `user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(40) DEFAULT NULL,
  `designation` varchar(50) DEFAULT NULL,
  `email` varchar(40) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `user` (`id`, `name`, `designation`, `email`) VALUES
(1, 'User1', 'Senior Manager', 'user1@gm.com'),
(2, 'User2', 'Head of IT', 'aru@rrg.com');

PhP Code

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Token input Demo</title>
<meta charset="utf-8">
<link
href="https://fonts.googleapis.com/css?family=Lato:400,700,300|Open+Sans:400,300,600,700"
rel="stylesheet" />
<link href="css/bootstrap.min.css?ver=3.3.5" rel="stylesheet" />
<link href="css/token-input.css" rel="stylesheet" />
</head>
<?php
error_reporting(0);
$con = mysqli_connect("localhost", "root", "", "rgcbres_accounts");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<script src="js/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="js/jquery.tokeninput.js"></script>
<script>
    $(document).ready(function () {
    $("#nameinput").tokenInput("tget-users.php", {       
    });
});
</script>
<body>
<div id="content" class="site-content">
<div class="container">
<h4>Token Input Demo</h4>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"
id="searchform" enctype="multipart/form-data">
<div class="col-sm-12">
<div class="form-group">
<label class="control-label col-sm-3" for="scst">Name <font
style="color: red;">*</font></label>
<div class="col-sm-6">
<div class="input-group">
<input type="text" id="nameinput" name="nameinput" required=""
class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="col-sm-6">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-default" name="Submit"
value="Submit">
</div>
</div>
</div>
</form>
<?php
if ($_POST['Submit']) {
    if (trim($_POST['nameinput']) != "") {
        $selected_name_arr = array();
        $selected_nameinput = $_POST['nameinput'];
        $selected_name_arr = explode(',', $selected_nameinput);       
        ?>  
            <div class="col-sm-12">
<form class="form-horizontal" id="saveform" action="#" method="post"
enctype="multipart/form-data">
<table id="editableTable" class="table table-bordered">
<thead>
<tr>
<td style="width: 5%;"><b>SL.No.</b></td>
<td style="background-color: #f0ad4e; width: 15%;"><b> Name </b></td>
<td style="background-color: #f0ad4e; width: 20%;"><b>
Designation </b></td>
<td style="background-color: #f0ad4e; width: 20%;"><b> Email </b></td>
</tr>
</thead>
<tbody>     
            <?php
        $sql = "SELECT * FROM user WHERE id IN (" . implode(',', $selected_name_arr) . ")";
        $result = $con->query($sql);
        $sino = 1;
        if ($result->num_rows > 0) {
            // output data of each row
            while ($row = $result->fetch_assoc()) {
                ?>
                    <tr>
<td><?php echo $sino; ?>                
<td><?php echo $row[name]; ?></td>
<td><?php echo $row[designation]; ?></td>
<td><?php echo $row[email]; ?></td>
</tr>
                 <?php
                $sino ++;
            }
        }
        ?>
            </tbody>
</table>
</div>
</form>           
            <?php
    }
}
?>
</div>
</div>
</body>
</html>


tget-users.php

<?php 
$con = mysqli_connect("localhost", "root", "", "rgcbres_accounts");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$users_arr = array();
$searchTerm = $_GET['q'];
     $query = $con->query("SELECT id,name FROM user  WHERE name LIKE '".$searchTerm."%' ORDER BY name ASC  LIMIT 15");  
    if($query->num_rows > 0){
        while($row = $query->fetch_assoc()){
            $users_arr[] = $row;
        }
    }    
    echo json_encode($users_arr);
?>     
    






Monday 25 April 2022

Export mysqli resultset as excel with nested table in PhP

 <?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$con = mysqli_connect("localhost", "root", "", "tablename");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$output = '';
$stmt3 = $con->prepare("SELECT id,registrationid,name,email,mobile,nationality,state,district,gender from adv33");
$stmt3->execute();
$stmt3->bind_result($id, $registrationid, $name, $email, $mobile, $nationality, $state, $district, $gender);
$stmt3->store_result();
if ($stmt3->num_rows > 0) {
    $output .= '
    <table border="1">
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Mobile</th>                      
                        <th>Nationality</th>
                        <th>State</th>
                        <th>District</th>
                        <th>Gender</th>                                            
                    </tr>
  ';
    while ($stmt3->fetch()) {
        $output .= '
                    <tr>                         
                         <td>' . $name . '</td>
                         <td>' . $email . '</td>
                         <td>' . $mobile . '</td>                         
                         <td>' . $nationality . '</td>
                         <td>' . $state . '</td>
                         <td>' . $district . '</td>
                         <td>' . $gender . '</td>                         
                    </tr>';
        $output .= '                  
         <table border="1">
         <tr>
         <td><b>Post</b></td>
         <td><b>Company</b></td>         
           <td><b>From Date</b></td>
            <td><b>To Date</b></td>
            <td><b>Scale of Pay</b></td>          
   ';
        $stmt4 = $con->prepare("SELECT slno,email,post,company,fromdate,todate,scale FROM adv33exp  where email ='$registrationid'");
        $stmt4->execute();
        /* bind result variables */
        $stmt4->bind_result($slno, $email, $post, $company, $fromdate, $todate, $scale);
        $stmt4->store_result();
        if ($stmt4->num_rows > 0) {
            /* fetch value */
            while ($stmt4->fetch()) {
                $output .= '
                     <tr>
                         <td>' . $post . '</td>
                         <td>' . $company . '</td>                        
                         <td>' . $fromdate . '</td>
                         <td>' . $todate . '</td>
                         <td>' . $scale . '</td>                         
                    </tr>
                ';
            }
        }
    }
    $output .= '</table>';
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=Applicants.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    echo $output;
}
?>

Sunday 24 April 2022

How to get hidden field value in jquery?

JS Code 

<script>

      $(document).ready(function(){   

        var userid = $('#userid').val();

    }

</script>

HTML Code

<input type="hidden" name="userid" id="userid" value="8"/>   

Friday 22 April 2022

Add dynamic rows in html table with Add, Edit, Delete feature in PHP and MySQLi

dynamic-table.php

<!DOCTYPE html>
<html lang="en-US">
<head>
<title> Dynamic Table in PhP</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,300|Open+Sans:400,300,600,700" rel="stylesheet" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<link href="../css/bootstrap.min.css?ver=3.3.5" rel="stylesheet" />
<link href="../css/font-awesome.min.css?ver=4.6.3" rel="stylesheet" />
<link rel="stylesheet" href="css/dataTables.bootstrap.min.css" />
</head>
<body>
<script src="../js/jquery-3.5.1.min.js"></script>
<script src="../js/jquery.dataTables.min.js"></script>
<script src="../js/bootstrap.min.js?ver=3.3.5"></script>
<script src="../js/jquery-ui.js"></script>
<script>
      $(document).ready(function(){
       $("#fromdate").datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'dd/mm/yy'                          
             
            });
        $("#todate").datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'dd/mm/yy'                          
             
            });
  var employeeData = $('#employeeList').DataTable({
"processing":true,
"serverSide":true,
"bFilter":false,
"bSort" : false ,
"bPaginate": false,
"bInfo" : false,
"order":[],
"ajax":{
url:"action.php",
type:"POST",
data:{action:'listEmployee'},
dataType:"json"
}
});
$('#addEmployee').click(function(){
$('#employeeModal').modal('show');
$('#employeeForm')[0].reset();
$('.modal-title').html("<i class='fa fa-plus'></i> Add Employment Details");
$('#action').val('addEmployee');
$('#save').val('Add');
});
$("#employeeList").on('click', '.update', function(){
var empId = $(this).attr("id");
var action = 'getEmployee';
$.ajax({
url:'action.php',
method:"POST",
data:{empId:empId, action:action},
dataType:"json",
success:function(data){
$('#employeeModal').modal('show');
$('#empId').val(data.id);
$('#post').val(data.post);
$('#company').val(data.company);
$('#type').val(data.type);
$('#fromdate').val(data.fromdate);
$('#todate').val(data.todate);
$('#scale').val(data.scale);
$('#gross').val(data.gross);
$('.modal-title').html("<i class='fa fa-plus'></i> Edit Employee");
$('#action').val('updateEmployee');
$('#save').val('Save');
}
})
});
$("#employeeModal").on('submit','#employeeForm', function(event){
event.preventDefault();
$('#save').attr('disabled','disabled');
var formData = $(this).serialize();
$.ajax({
url:"action.php",
method:"POST",
data:formData,
success:function(data){
$('#employeeForm')[0].reset();
$('#employeeModal').modal('hide');
$('#save').attr('disabled', false);
employeeData.ajax.reload();
}
})
});
$("#employeeList").on('click', '.delete', function(){
var empId = $(this).attr("id");
var action = "empDelete";
if(confirm("Are you sure you want to delete this employee?")) {
$.ajax({
url:"action.php",
method:"POST",
data:{empId:empId, action:action},
success:function(data) {
employeeData.ajax.reload();
}
})
} else {
return false;
}
});
});
</script>
<div id="content" class="site-content">
<div class="container">
<div class="row">
<div class="col-md-12 padding-bottom-20">
<div class="row row-margin">
<div class="col-md-12">
<div class="container">
<div id="payment" style="display: block;">
<div style="overflow-x: auto;">
<div class="col-lg-10 col-md-10 col-sm-9 col-xs-12">   
<div class="panel-heading">
<div class="row">
<div class="col-md-10">
<h3 class="panel-title"></h3>
</div>
<div class="col-md-2" align="right">
<button type="button" name="add" id="addEmployee" class="btn btn-success btn-xs" style="font-size: 15px;padding: 10%;">Add New Row</button>
</div>
</div>
</div>
<table id="employeeList" class="table table-bordered table-striped" style="width:100%;">
        <thead>
<tr>
<th>Post held</th>
<th>Department/ Institute/ Company</th>
<th>Permanent/ Temporary/ Contract</th>
<th>From Date</th>
<th>To Date</th>
<th>Scale of pay</th>
<th>Gross Amount</th>
<th></th>
<th></th>
</tr>
</table>
</div>
<div id="employeeModal" class="modal fade">
    <div class="modal-dialog">
    <form method="post" id="employeeForm">
    <div class="modal-content">
    <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title"><i class="fa fa-plus"></i> Edit Employment Details</h4>
    </div>
    <div class="modal-body">
<div class="form-group"
<label for="post" class="control-label">Post held</label>
<input type="text" class="form-control" id="post" name="post" placeholder="Post held" required>
</div>
<div class="form-group">
<label for="company" class="control-label">Department/ Institute/ Company</label>
<input type="text" class="form-control" id="company" name="company" placeholder="Department/ Institute/ Company">
</div>    
<div class="form-group">
<label for="type" class="control-label">Permanent/ Temporary/ Contract</label>
<input type="text" class="form-control"  id="type" name="type" placeholder="Permanent/ Temporary/ Contract" required="required">
</div>  
<div class="form-group">
<label for="fromdate" class="control-label">From Date [dd/mm/yyyy]</label>
<input type="text" class="form-control"  id="fromdate" name="fromdate" placeholder="From Date" autocomplete="off" readonly="readonly" required="required" ></textarea>
</div>
<div class="form-group">
<label for="todate" class="control-label">To Date [dd/mm/yyyy]</label>
<input type="text" class="form-control" id="todate" name="todate" placeholder="To Date" autocomplete="off" readonly="readonly" required="required" >
</div>
<div class="form-group">
<label for="scale" class="control-label">Scale of pay</label>
<input type="text" class="form-control" id="scale" name="scale" placeholder="Scale of pay" required="required" >
</div>
<div class="form-group">
<label for="gross" class="control-label">Gross Amount</label>
<input type="text" class="form-control" id="gross" name="gross" placeholder="Gross Amount" required="required" >
</div>
    </div>
    <div class="modal-footer">
    <input type="hidden" name="empId" id="empId" />
    <input type="hidden" name="userid" id="userid" value="12"/>   
    <input type="hidden" name="action" id="action" value="" />
    <input type="submit" name="save" id="save" class="btn btn-info" value="Save" />
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    </div>
    </div>
    </form>
    </div>
    </div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- .col-md-9 --></div>
<!-- .row --></div>
<!-- .container --></div>

action.php

<?php
include('Employee.php');
$emp = new Employee();
if(!empty($_POST['action']) && $_POST['action'] == 'listEmployee') {
$emp->employeeList();
}
if(!empty($_POST['action']) && $_POST['action'] == 'addEmployee') {
$emp->addEmployee();
}
if(!empty($_POST['action']) && $_POST['action'] == 'getEmployee') {
$emp->getEmployee();
}
if(!empty($_POST['action']) && $_POST['action'] == 'updateEmployee') {
$emp->updateEmployee();
}
if(!empty($_POST['action']) && $_POST['action'] == 'empDelete') {
$emp->deleteEmployee();
}
?>

Config.php

<?php
class dbConfig {
    protected $serverName;
    protected $userName;
    protected $password;
    protected $dbName;
    function dbConfig() {
        $this -> serverName = 'localhost';
        $this -> userName = 'root';
        $this -> password = "";
        $this -> dbName = "employee";
    }
}
?>

Employee.php

<?php require('config.php'); class Employee extends Dbconfig { protected $hostName; protected $userName; protected $password; protected $dbName; private $empTable = 'employment'; private $dbConnect = false; public function __construct(){ if(!$this->dbConnect){ $database = new dbConfig(); $this -> hostName = $database -> serverName; $this -> userName = $database -> userName; $this -> password = $database ->password; $this -> dbName = $database -> dbName; $conn = new mysqli($this->hostName, $this->userName, $this->password, $this->dbName); if($conn->connect_error){ die("Error failed to connect to MySQL: " . $conn->connect_error); } else{ $this->dbConnect = $conn; } } } public function employeeList(){ $sqlQuery = "SELECT * FROM ".$this->empTable." "; $result = mysqli_query($this->dbConnect, $sqlQuery); $employeeData = array(); while( $employee = mysqli_fetch_assoc($result) ) { $empRows = array(); $empRows[] = $employee['post']; $empRows[] = $employee['company']; $empRows[] = $employee['type']; $empRows[] = $employee['fromdate']; $empRows[] = $employee['todate']; $empRows[] = $employee['scale']; $empRows[] = $employee['gross']; $empRows[] = '<button type="button" name="update" id="'.$employee["id"].'" class="btn btn-warning btn-xs update">Update</button>'; $empRows[] = '<button type="button" name="delete" id="'.$employee["id"].'" class="btn btn-danger btn-xs delete" >Delete</button>'; $employeeData[] = $empRows; } $output = array( "draw" => intval($_POST["draw"]), "data" => $employeeData ); echo json_encode($output); } public function getEmployee(){ if($_POST["empId"]) { $sqlQuery = " SELECT * FROM ".$this->empTable." WHERE id = '".$_POST["empId"]."'"; $result = mysqli_query($this->dbConnect, $sqlQuery); $row = mysqli_fetch_array($result, MYSQLI_ASSOC); echo json_encode($row); } } public function updateEmployee(){ if($_POST['empId']) { $updateQuery = "UPDATE ".$this->empTable." SET userid = '".$_POST["userid"]."', post = '".$_POST["post"]."', company = '".$_POST["company"]."', type = '".$_POST["type"]."', fromdate = '".$_POST["fromdate"]."' , todate = '".$_POST["todate"]."' , scale = '".$_POST["scale"]."', gross = '".$_POST["gross"]."' WHERE id ='".$_POST["empId"]."'"; $isUpdated = mysqli_query($this->dbConnect, $updateQuery); } } public function addEmployee(){ $insertQuery = "INSERT INTO ".$this->empTable." (userid, post, company, type, fromdate, todate,scale, gross) VALUES ('".$_POST["userid"]."','".$_POST["post"]."', '".$_POST["company"]."', '".$_POST["type"]."', '".$_POST["fromdate"]."', '".$_POST["todate"]."', '".$_POST["scale"]."', '".$_POST["gross"]."')"; $isUpdated = mysqli_query($this->dbConnect, $insertQuery); } public function deleteEmployee(){ if($_POST["empId"]) { $sqlDelete = " DELETE FROM ".$this->empTable." WHERE id = '".$_POST["empId"]."'"; mysqli_query($this->dbConnect, $sqlDelete); } } } ?>

employee.sql

CREATE TABLE `employment` (
  `id` int(10) NOT NULL,
  `userid` int(10) DEFAULT NULL,
  `post` varchar(100) DEFAULT NULL,
  `company` varchar(100) DEFAULT NULL,
  `type` varchar(25) DEFAULT NULL,
  `fromdate` varchar(25) DEFAULT NULL,
  `todate` varchar(25) DEFAULT NULL,
  `scale` varchar(50) DEFAULT NULL,
  `gross` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


Tuesday 19 April 2022

Fatal error: Cannot redeclare Function() in PhP

Fatal error: Cannot redeclare count_words() (previously declared) in PhP
Solution
1. Don't declare a function inside a loop. Declare before them.
or
You should include the file (wherein that function exists) only once. So instead of
include ("function.php");
use     
include_once("function.php");


Monday 18 April 2022

Integrate TinyMCE Editor in PhP

1. Download the latest version of TinyMCE SDK 

    https://www.tiny.cloud/get-tiny/

2. Extract the folder [tinymce] and put in your application root folder.

eg: C:\xampp\htdocs\tinymcedemo\tinymce [tinymcedemo is the root folder]

3. Create a php file "test.php" and place the below code 

<!DOCTYPE html>
<html>
<head>
  <script src="tinymce/tinymce.min.js"></script>
  <script type="text/javascript">
  tinymce.init({
    selector: '#mytextarea'
  });
  </script>
</head>
<body>
  <h1>TinyMCE </h1>
  <form method="post">
    <textarea id="mytextarea"></textarea>
  </form>
</body>
</html>

How to disable phpinfo() in a hosting environment?

Login to server WHM as a root user

Edit the php.ini file. Add below line

disable_functions = phpinfo

Restart the server

Friday 15 April 2022

Fatal error: Cannot pass parameter by reference in PHP

Fatal error: Cannot pass parameter  by reference in PHP.

$stmt->bind_param("ssss",$userid,$theme,$title,"test");

The error is with 'test' in the bind_param call.

All parameters to bind_param must be passed by reference. A string is a primitive value, and cannot be passed by reference.

You can fix this by creating a variable and passing that as a parameter instead:

$testvar="test";

$stmt->bind_param("ssss",$userid,$theme,$title,$testvar);

Enable or disable the "Powered by TinyMCE" branding.

Tinymce branding property allow you to enable or disable the "Powered by TinyMCE" branding.

tinymce.init({
  selector: 'textarea',  
  branding: false
});

Thursday 14 November 2019

Adding Excel export button hides/removes the Page Length Dropdown in Data Tables

Add below line in javascript table initialization

"dom": '<"top"Bf>rt<"bottom"lip><"clear">'

Complete Code 
<script>
        $(document).ready(function () {       
        $('#example').DataTable( {
                "processing": true,               
                "lengthMenu": [[25, 50, -1], [ 25, 50, "All"]],
                "dom": '<"top"Bf>rt<"bottom"lip><"clear">',
                "serverSide": true,
                "ajax": "server_processing.php"
            } );
        });                     

</script>

Thursday 24 April 2014

Add image/logo in browser tab for website

How to add image/logo in browser tab for website?

Place the below code under <head> tag in html

<link rel="shortcut icon" href="path to your logo">

Sunday 27 October 2013

Keep checkbox checked after submit refresh in PHP

Below code maintain checkbox value when user click preview button


<?php
    if (isset($_POST['number']))
    {
        foreach ($_POST['number'] as $selectednumber)
            $selected[$selectednumber] = "checked";
    }
?>

<form action="" method="post">
    <input type="checkbox" name="number[]" <?php echo $selected['one'] ?> value="one" />one<br />
    <input type="checkbox" name="number[]" <?php echo $selected['two'] ?> value="two" />two<br />
    <input type="checkbox" name="number[]" <?php echo $selected['three'] ?> value="three" />three<br />
    <input type="checkbox" name="number[]" <?php echo $selected['four'] ?> value="four" />four<br />

<input type="submit" name="Submit" value="Preview" />
</form>

Friday 25 October 2013

How to get previous page url in PHP

$realname = basename($_SERVER['HTTP_REFERER'], ".php");

Multiple submit button in a single form in PHP

<form method="post">
<input type="submit" name="save" value="Submit 1">
<input type="submit" name="cancel" value="Submit 2">
</form>


<?php
if (isset($_POST['save'])) {
  // code
}
else if (isset($_POST['cancel'])) {
  // code
}
?>

Friday 4 October 2013

Fatal error: Call to undefined function http_redirect() : Fixed

Issue: When I was trying to call the PHP http_redirect() function, below error came up:

Fatal error: Call to undefined function http_redirect() in location.


Add the below function in your php page

/**
 * redirect to a specific URL
 * @param $url
 */
     
function redirect($url)
{
     if (!
headers_sent())
     {  
          
//If headers not sent yet... then do php redirect
          
header('Location: '.$url); exit;
     }
     else
     {                  
          
//If headers are sent... do javascript redirect...
          //if javascript disabled, do html redirect.
          
echo '<script type="text/javascript">';
          echo 
'window.location.href="'.$url.'";';
          echo 
'</script>';
          echo 
'<noscript>';
          echo 
'<meta http-equiv="refresh" content="0;url='.$url.'" />';
          echo 
'</noscript>'; exit;
     }
}  


then call the above function  to the page you wish the redirect to happen on

eg: redirect("redirect.php");