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);
?>