Printing a receipt PHP - php

I have a working php form which also has a button that opens a windows to take a fee from an account.
Is it possible to setup an auto print feature where as soon as the form process is done then the user is taken to a print screen. The only solution i could find is to print the whole screen but I would prefer to design the receipt myself. Would FPDF work in this regard?
Below is the Fees.php form code:
<link rel="shortcut icon" href="img/icon.ico" type="image/x-icon"/>
<?php
include("php/dbconnect.php");
$errormsg= '';
if(isset($_POST['save']))
{
$paid = mysqli_real_escape_string($conn,$_POST['paid']);
$submitdate = mysqli_real_escape_string($conn,$_POST['submitdate']);
$transcation_remark =
mysqli_real_escape_string($conn,$_POST['transcation_remark']);
$sid = mysqli_real_escape_string($conn,$_POST['sid']);
$sql = "select fees,balance from student where id = '$sid'";
$sq = $conn->query($sql);
$sr = $sq->fetch_assoc();
$totalfee = $sr['fees'];
if($sr['balance']>0)
{
$sql = "insert into
fees_transaction(stdid,submitdate,transcation_remark,paid)
values('$sid','$submitdate','$transcation_remark','$paid') ";
$conn->query($sql);
$sql = "SELECT sum(paid) as totalpaid FROM fees_transaction WHERE stdid = '$sid'";
$tpq = $conn->query($sql);
$tpr = $tpq->fetch_assoc();
$totalpaid = $tpr['totalpaid'];
$tbalance = $totalfee - $totalpaid;
$sql = "update student set balance='$tbalance' where id = '$sid'";
$conn->query($sql);
echo '<script type="text/javascript">window.location="fees.php?act=1";</script>';
}
}
if(isset($_REQUEST['act']) && #$_REQUEST['act']=="1")
{
$errormsg = "<div class='alert alert-success'><a href='#' class='close'
data-dismiss='alert' aria-label='close'>×</a><strong>Success!</strong>
Fees submit successfully</div>";
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Accounts | iBroker Finance</title>
<!-- BOOTSTRAP STYLES-->
<link href="css/bootstrap.css" rel="stylesheet" />
<!-- FONTAWESOME STYLES-->
<link href="css/font-awesome.css" rel="stylesheet" />
<!--CUSTOM BASIC STYLES-->
<link href="css/basic.css" rel="stylesheet" />
<!--CUSTOM MAIN STYLES-->
<link href="css/custom.css" rel="stylesheet" />
<!-- GOOGLE FONTS-->
<link href='http://fonts.googleapis.com/css?family=Open+Sans'
rel='stylesheet' type='text/css' />
<link href="css/ui.css" rel="stylesheet" />
<link href="css/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" />
<link href="css/datepicker.css" rel="stylesheet" />
<link href="css/datatable/datatable.css" rel="stylesheet" />
<script src="js/jquery-1.10.2.js"></script>
<script type='text/javascript' src='js/jquery/jquery-ui-1.10.1.custom.min.js'></script>
<script type="text/javascript" src="js/validation/jquery.validate.min.js">
</script>
<script src="js/dataTable/jquery.dataTables.min.js"></script>
</head>
<?php
include("php/header.php");
?>
<div id="page-wrapper">
<div id="page-inner">
<div class="row">
<div class="col-md-12">
<h1 class="page-head-line">Manage Accounts
</h1>
</div>
</div>
<?php
echo $errormsg;
?>
<div class="row" style="margin-bottom:20px;">
<div class="col-md-12">
<fieldset class="scheduler-border" >
<legend class="scheduler-border">Search:</legend>
<form class="form-inline" role="form" id="searchform">
<div class="form-group">
<label for="email">Name</label>
<input type="text" class="form-control" id="student" name="student">
</div>
<div class="form-group">
<label for="email"> Date Of Joining </label>
<input type="text" class="form-control" id="doj" name="doj" >
</div>
<div class="form-group">
<label for="email"> Branch </label>
<select class="form-control" id="branch" name="branch" >
<option value="" >Select Branch</option>
<?php
$sql = "select * from branch where delete_status='0' order by branch.branch asc";
$q = $conn->query($sql);
while($r = $q->fetch_assoc())
{
echo '<option value="'.$r['id'].'" '.(($branch==$r['id'])?'selected="selected"':'').'>'.$r['branch'].'</option>';
}
?>
</select>
</div>
<button type="button" class="btn btn-success btn-sm" id="find" > Find
</button>
<button type="reset" class="btn btn-danger btn-sm" id="clear" > Clear
</button>
</form>
</fieldset>
</div>
</div>
<script type="text/javascript">
$(document).ready( function() {
/*
$('#doj').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: false,
dateFormat: 'mm/yy',
onClose: function(dateText, inst) {
$(this).datepicker('setDate', new Date(inst.selectedYear,
inst.selectedMonth, 1));
}
});
*/
/******************/
$("#doj").datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'mm/yy',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month
:selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year
:selected").val();
$(this).val($.datepicker.formatDate('MM yy', new Date(year, month,
1)));
}
});
$("#doj").focus(function () {
$(".ui-datepicker-calendar").hide();
$("#ui-datepicker-div").position({
my: "center top",
at: "center bottom",
of: $(this)
});
});
/*****************/
$('#student').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajx.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'studentname'
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
}
/*,
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var abc = ui.item.label.split("-");
//alert(abc[0]);
$("#student").val(abc[0]);
return false;
},
*/
});
$('#find').click(function () {
mydatatable();
});
$('#clear').click(function () {
$('#searchform')[0].reset();
mydatatable();
});
function mydatatable()
{
$("#subjectresult").html('<table class="table table-striped table-bordered table-hover" id="tSortable22"><thead><tr><th>Name/Contact</th> <th>Premium Amount Incl Stamp Fee</th><th>Oustanding</th><th>Branch</th><th>Joining Date</th><th>Action</th></tr></thead><tbody></tbody></table>');
$("#tSortable22").dataTable({
'sPaginationType' : 'full_numbers',
"bLengthChange": false,
"bFilter": false,
"bInfo": false,
'bProcessing' : true,
'bServerSide': true,
'sAjaxSource':
"datatable.php?"+$('#searchform').serialize()+"&type=feesearch",
'aoColumnDefs': [{
'bSortable': false,
'aTargets': [-1] /* 1st one, start by the
right */
}]
});
}
////////////////////////////
$("#tSortable22").dataTable({
'sPaginationType' : 'full_numbers',
"bLengthChange": false,
"bFilter": false,
"bInfo": false,
'bProcessing' : true,
'bServerSide': true,
'sAjaxSource': "datatable.php?type=feesearch",
'aoColumnDefs': [{
'bSortable': false,
'aTargets': [-1] /* 1st one, start by the right */
}]
});
///////////////////////////
});
function GetFeeForm(sid)
{
$.ajax({
type: 'post',
url: 'getfeeform.php',
data: {student:sid,req:'1'},
success: function (data) {
$('#formcontent').html(data);
$("#myModal").modal({backdrop: "static"});
}
});
}
</script>
<style>
#doj .ui-datepicker-calendar
{
display:none;
}
</style>
<div class="panel panel-default">
<div class="panel-heading">
Account Management
</div>
<div class="panel-body">
<div class="table-sorting table-responsive"
id="subjectresult">
<table class="table table-striped table-bordered
table-hover" id="tSortable22">
<thead>
<tr>
<th>Name/Payment Plan</th>
<th>Premium Amount Incl Stamp
Fee</th>
<th>Outstanding</th>
<th>Insurer</th>
<th>Joining Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<!-------->
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×
</button>
<h4 class="modal-title">Take Fee</h4>
</div>
<div class="modal-body" id="formcontent">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!--------->
</div>
<!-- /. PAGE INNER -->
</div>
<!-- /. PAGE WRAPPER -->
</div>
<!-- /. WRAPPER -->
<div id="footer-sec">
iBroker Finance System | Developed By Siyakha Technology
</div>
<!-- BOOTSTRAP SCRIPTS -->
<script src="js/bootstrap.js"></script>
<!-- METISMENU SCRIPTS -->
<script src="js/jquery.metisMenu.js"></script>
<!-- CUSTOM SCRIPTS -->
<script src="js/custom1.js"></script>
</body>
</html>

For print styling, use the print media query
#media print {
body {
background-color: lightgreen;
}
}
Another way would be to link existing css file with the print media attribute
<link rel="stylesheet" type="text/css" media="print" href="print.css">
And for auto printing, just use window.print() in your js code

Related

How Do I Merge Two Images WIth PHP GD Library and Return a Json Output As Result

I have been able to implement the same UI Logic for the Web App I found on this URL, and now I am stuck on the Backend Logic that generated the Merged images (i.e the Cropped Image and the placeholder image as seen on the page) and Renders it to the DOM.
As it is right now, my AJAX never resolves with the success callback, instead, it always resolves with the error callback and I have no clue what I am doing wrong, please?
How can I achieve exactly the same backend logic has seen from the web app in this URL:
https://rhapsodyofrealities.org/rhapathon/?
Using PHP, this is what I have so far for the Backend Logic.
Problem with this method is, it tries to output the image directly to the page:
$targetDir = "uploads/";
$fileName = $targetDir.'complete_'.time().".png";
if(isset($_POST['image'])) {
$placeholder = './rhapathon.jpeg';
$src = $_POST['image'];
list($width, $height) = getimagesize($src);
// $placeholder = imagecreatefromstring(file_get_contents($placeholder));
$placeholder = imagecreatefromjpeg($placeholder);
// $src = imagecreatefromstring(file_get_contents($src));
$src = imagecreatefrompng($src);
imagecopy($placeholder, $src, 200, 200, 0, 0, 300, 300);
header('Content-Type: image/png');
// $imgobj = array("img" => imagepng($placeholder, $fileName));
// $result = json_encode($imgobj);
// echo $result;
imagepng($placeholder);
// Free Memory
imagedestroy($placeholder);
imagedestroy($src);
}
?>
My HTML with the Entire UI and Client Logic:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<meta name=description content="Christ Embassy Kubwa Church">
<meta name=viewport content="width=device-width, initial-scale=1">
<title>Good Miracle Friday Crusade Flyer Generator</title>
<!-- <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap-reboot.min.css"> -->
<!-- <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap-grid.min.css"> -->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css">
<!-- <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.4/croppie.css"> -->
<link rel="stylesheet" type="text/css" href="./node_modules/croppie/croppie.css">
<link rel="stylesheet" type="text/css" href="./index.css">
</head>
<body>
<!-- Header -->
<header class="container-fluid p-0 text-center rounded-0 m-0 mb-5">
<div class="jumbotron p-2 bg-info rounded-0 m-0">
<h1 class="font-weight-lighter display-5 text-white">GOOD MIRACLE FRIDAY CRUSADE</h1>
</div>
</header>
<!-- /Header -->
<div class="container">
<!-- Card -->
<div class="card mx-auto rounded-top rounded-bottom" style="overflow: hidden;">
<!-- Card-Head -->
<div class="card-heading bg-dark text-white p-2 lead font-weight-light">Create Avatar</div>
<!-- /card-Head -->
<!-- Card-Body -->
<div class="card-body">
<div class="row">
<div class="col-md-4 text-center">
<div id="upload-demo" style="width:350px"></div>
</div>
<!-- Col -->
<div class="col-md-4" style="padding-top:30px;">
<div class="mt-0 mb-5">
<strong>STEP 1 : Select Image and adjust to fit</strong>
<input type="file" id="upload" name="fileToUpload">
</div>
<div class="mt-0 mb-5">
<strong>STEP 2 : Upload Image and Download</strong>
<br>
<button class="btn btn-info upload-result">Upload Image</button>
</div>
</div>
<!-- /Col -->
<!-- Col -->
<div class="col-md-4">
<div id="upload-demo-i" style="background:url('./rhapathon.jpeg'); background-size: 300px 300px; width:300px;height:300px;margin-top:30px">
</div>
</div>
<!-- /Col -->
</div>
</div>
</div>
</div>
<!-- Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.4/croppie.js"></script> -->
<script src="./node_modules/croppie/croppie.js"></script>
<!-- <script src="./node_modules/html2canvas/dist/html2canvas.min.js"></script> -->
<!-- <script src="./node_modules/canvas2image/canvas2image.js"></script> -->
<script src="./index.js"></script>
<script type="text/javascript">
$uploadCrop = $('#upload-demo').croppie({
enableExif: true,
enableOrientation: true,
viewport: {
width: 300,
height: 300,
type: 'circle'
},
boundary: {
width: 300,
height: 300
}
});
$('#upload').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
$uploadCrop.croppie('bind', {
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.upload-result').on('click', function (ev) {
console.log('Uploading image');
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport',
}).then(function (resp) {
$.ajax({
url: "upload.php",
type: "POST",
data: {"image":resp},
dataType:'JSON',
success: function (data) {
console.log('response ='+data.img);
// html = '<img src="' + resp + '" />';
// $("#upload-demo-i").html(html);
html = '<img width="300px" src="' + data.img + '" /><button style="margin-top:20px; margin-bottom:100px" class="btn btn-danger upload-result">Download Avatar</button> <button style="margin-top:-50px; margin-bottom:100px" class="btn btn-info upload-result">Proceed to Rhapsody Official Website</button>';
$("#upload-demo-i").html(html);
},
error: function (err) {
console.error('Error occured: ', err);
}
});
});
});
// Remove alt attribute from image
window.onload = () => {
document.querySelector('.cr-image').removeAttribute("alt");
document.querySelector('.cr-slider').value="0";
document.querySelector('.cr-slider').focus();
};
</script>
</body>
</html>
after save image file add this lines:
$image_file = fopen($fileName, 'r');
$image_data = fread($image_file, filesize($fileName));
header("Content-type: application/json");
echo json_encode(['img' -> 'data:image/jpeg;base64,' . base64_encode($image_data) );
And if you have problem with merge images look at : Merge two PNG images with PHP GD library

Ajax code not working as intended on first run

I have an Ajax script on a PHP page which is to run a php script on clicking a button.
The code is as follows:
<script>
$('#signup-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'insertfromsession.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data){
$('#form-container').fadeOut('slow', function(){
$('#form-container').fadeIn('slow').html(data);
});
document.getElementById('submitBtn').disabled = true;
document.getElementById("submitBtn").value="Thanks!";
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
When I first open the web page the script isn't run, but if i click back and repeat the process the script executes without an issue. Does anyone know what is causing the issue?
Insert.php which runs this code is here:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/submit.js"></script>
<!-- /.website title -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<!-- CSS Files -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="fonts/icon-7-stroke/css/pe-icon-7-stroke.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet" media="screen">
<link href="css/owl.theme.css" rel="stylesheet">
<link href="css/owl.carousel.css" rel="stylesheet">
<style type="text/css">
body { background: white !important; } /* Adding !important forces the browser to overwrite the default style applied by Bootstrap */
</style>
<!-- Colors -->
<link href="css/css-index.css" rel="stylesheet" media="screen">
<!-- <link href="css/css-index-green.css" rel="stylesheet" media="screen"> -->
<!-- <link href="css/css-index-purple.css" rel="stylesheet" media="screen"> -->
<!-- <link href="css/css-index-red.css" rel="stylesheet" media="screen"> -->
<!-- <link href="css/css-index-orange.css" rel="stylesheet" media="screen"> -->
<!-- <link href="css/css-index-yellow.css" rel="stylesheet" media="screen"> -->
<!-- Google Fonts -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic" />
</head>
<div id="top"></div>
<div class="fullscreen landing parallax" style="background-image:url('images/fireworks.jpg');" data-img-width="2000" data-img-height="1333" data-diff="100">
<div class="overlay">
<div class="container">
<div class="row">
<div class="col-md-10">
<!-- /.logo -->
<!-- /.main title -->
<h2 class="wow fadeInLeft">Thank you for submitting your details</h2>
<h2 class="wow bounce infinite">While you are here, why not apply for one of other fantastic products?</h2>
<?php
session_start();
include ("dbconnect.php");
// prepare and bind
$stmt = $conn->prepare("INSERT INTO wills (forename,surname,postcode,telno,email,ipaddress,capturedate,url,user) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssssss", $forename, $surname, $postcode, $telno, $email, $ipaddress, $capturedate, $url, $user);
$forename = $_POST["forename"];
$surname = $_POST["surname"];
$postcode = $_POST["postcode"];
$telno = $_POST["telno"];
$email = $_POST["email"];
$ipaddress = $_SERVER['REMOTE_ADDR'];
$capturedate = date('Y-m-d H:i:s');
$url ="www.test.com";
$user ="testuser";
$_SESSION["forename"] = $forename;
$_SESSION["surname"] = $surname;
$_SESSION["postcode"] = $postcode;
$_SESSION["telno"] = $telno;
$_SESSION["email"] = $email;
$_SESSION["ipaddress"] = $ipaddress;
$_SESSION["capturedate"] = $capturedate;
$_SESSION["url"] = $url;
$_SESSION["user"] = $user;
echo "<br>"."Forename: ".$forename."<br>";
echo "Surname: ".$surname."<br>";
echo "Telno: ".$telno."<br>";
echo "Email: ".$email."<br>";
echo "IP Address: ".$ipaddress."<br>";
echo "Session User: ".$_SESSION["user"]."<br>";
if (!$stmt->execute()) {
echo $stmt->error;
} else {
}
$stmt->close();
$conn->close();
?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="text-center">Back to Main Page</div>
<div class="col-md-12">
<!-- /.product 1 -->
<div class="col-sm-6 feat-list">
<i class="pe-7s-phone pe-5x pe-va wow fadeInUp"></i>
<div class="inner">
<h4>Grab a Mobile SIM</h4>
<p>With a SIM only contract, you get the all the benefits of an ongoing contract, without the additional high cost of a handset.
Short-term SIM only contracts give you freedom and flexibility. All the networks offer them from as little as 30 days, and you can then keep them rolling month-by-month
</p>
<form method="post" id="signup-form" autocomplete="off">
<div class="form-group">
<input type="submit" class="btn btn-success btn-block btn-lg" id="submitBtn" value="Apply for Mobile Sim?">
</div>
</form>
</div>
</div>
<!-- /.product 2 -->
<div class="col-sm-6 feat-list">
<i class="pe-7s-like2 pe-5x pe-va wow fadeInUp"></i>
<div class="inner">
<h4>Debt Plan</h4>
<p>Do you have more than &pound5,000 worth of debt?<br>
Do you need help to reduce the monthly payments?<br>
If so, find out if you qualify to write off up to 80% of your debt here</p>
<form method="post" id="signup-formdebt" autocomplete="off">
<div class="form-group">
<input type="submit" class="btn btn-success btn-block btn-lg" id="submitBtndebt" value="Get help now">
</div>
</form>
</div>
</div>
</div>
<!-- /.footer -->
<footer id="footer">
<div class="container">
<div class="col-sm-4 col-sm-offset-4">
<!-- /.social links -->
<div class="social text-center">
<ul>
<li><a class="wow fadeInUp" href="https://twitter.com/"><i class="fa fa-twitter"></i></a></li>
<li><a class="wow fadeInUp" href="https://www.facebook.com/" data-wow-delay="0.2s"><i class="fa fa-facebook"></i></a></li>
</ul>
</div>
<i class="pe-7s-up-arrow pe-va"></i>
</div>
</div>
</footer>
<!-- /.javascript files -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/custom.js"></script>
<script src="js/jquery.sticky.js"></script>
<script src="js/wow.min.js"></script>
<script src="js/owl.carousel.min.js"></script>
<script>
new WOW().init();
</script>
</body>
<script>
$( document ).ready(function() {
$('#signup-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'insertfromsession.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data){
$('#form-container').fadeOut('slow', function(){
$('#form-container').fadeIn('slow').html(data);
});
document.getElementById('submitBtn').disabled = true;
document.getElementById("submitBtn").value="Thanks!";
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
});
</script>
<script>
$( document ).ready(function() {
console.log( "ready!" );
$('#signup-formdebt').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'insertfromsessiondebt.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data){
$('#form-container').fadeOut('slow', function(){
$('#form-container').fadeIn('slow').html(data);
});
document.getElementById('submitBtndebt').disabled = true;
document.getElementById("submitBtndebt").value="Thanks!";
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
});
</script>
</html>
I think I solved the issue and it has nothing at all to do with the AJAX. It actually appears to be an issue with the session variables. I moved the session variables on the insert.php right to the top before anything else and this makes it work as intended.
Thanks for your efforts guys
You should use a document.ready function. Here is a link to the jQuery version documentation : https://learn.jquery.com/using-jquery-core/document-ready/

How to add Total Cell at the bottom of Jquery Datatable

I need datatable to be implemented in my project. I wanna show total number at the bottom of the table like below:
I already make default data table like this :
This is my code.
<?php
include "db.php";
$obj->tglan=$obj->get_hari();
if (isset($_POST['tanggal2'])) {
$obj->tglan = $_POST['tanggal2'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="assets/DataTables/media/js/jquery.js"></script>
<script type="text/javascript" src="assets/DataTables/media/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="assets/DataTables/media/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="assets/DataTables/media/css/dataTables.bootstrap.css">
<link rel="stylesheet" href="assets/css/bootstrap.min.css"/>
<link rel="stylesheet" href="assets/datepicker/css/bootstrap-datepicker3.css"/>
</head>
<body>
<center>
<h3>Daftar SPTA<br><?php echo $obj->tanggal("D, j M Y",$obj->tglan);?></h3>
</center>
<left>
<h5>&nbsp&nbsp&nbspLast refreshed : <?php echo $obj->tanggal("D, j M Y",$obj->tglan)." ".date("H:i:s");?></h5>
</left>
<br/>
<form action="viewLaporanUtama2.php" method="POST">
<div class="form-group" >
<label for="tanggal">&nbsp&nbsp&nbspTanggal</label>
<input type="text" name="tanggal1" class="tanggal" id="myText" required/>
<input type="submit" name="enter" value="Cari" class="btn btn-info btn-sm">
</div>
</form>
<div class="container-fluid">
<div class="table-responsive">
<table border = '0' class="table table-striped table-bordered data" id="tabelSpta">
<thead>
<tr>
<th>No</th>
<th>No SPTA</th>
<th>No Register Induk</th>
<th>Nama Petani</th>
<th>Gawang/Pos</th>
<th>Timbang Bruto</th>
<th>Giling</th>
<th>Timbang Tarra</th>
<th>Netto(kw)</th>
<th>Kode Rafraksi</th>
<th>Potongan (kw)</th>
<th>Netto Akhir (kw)</th>
</tr>
</thead>
<tbody>
<div id="bagReload">
<?php
echo $obj->tampilLaporan();
?>
</div>
</tbody>
</table>
</div>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
var tabel = $('.data').DataTable();
});
</script>
<!-- <script src="js/jquery-3.2.1.min.js"></script> -->
<script src="assets/js/bootstrap.js"></script>
<script src="assets/datepicker/js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.tanggal').datepicker({
format: "yyyy-mm-dd",
autoclose:true
});
});
</script>
</html>
I've already searched but, there's few reference but I couldn't understand that
How I can add Total cell and show at the bottom of datatable?
See this example here http://jsbin.com/putiyep/edit?js,output written by bindrid.
http://jsbin.com/putiyep/edit?js,output
Basically it leverages the footerCallback of the API and use the column index of the table and basic math to return your total.
Excerpt of the code (again not my code):
// Table definition
var dtapi = $('#example').DataTable({
data: dataSet,
pageLength: 3,
"deferRender": false,
"footerCallback": function (tfoot, data, start, end, display) {
var api = this.api();
var p = api.column(4).data().reduce(function (a, b) {
return a + b;
}, 0)
$(api.column(4).footer()).html(p);
$("#total").val(p);
},
"order": [1],
"columns": [
// rest of the columns
{ data: "first_name" },
{ data: "last_name" },
{ data: "firstNumber" },
{
data: "secondNumber", render: function (data) {
return '<input type="text" style="width:50px" value="' + data + '">';
}
},
{ data: "rowTotal" }
]
});

AutoComplete input data php/jquery/mysqli

I have made this application in which to look for a result and with jquery autocomplete me. What do I want to know is that when autocomplete the first "cari_keyword_id" field and click me automatically fill the other input, which is the user ID. How is possible?? I need the second step, taking the first field autocomplete filled.
I hope you can help me or give me information!
greetingS!!!
CODE
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Autocomplete Search dengan PHP, MySQLi, Ajax and jQuery </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet" media="screen">
<link href="assets/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="../assets/js/html5shiv.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="brand" href="http://andeznet.com">AndezNet</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li>Home</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<div class='web'>
<input type="text" class="cari_keyword form-control" id="cari_keyword_id" placeholder="Cari Nama Siswa..." />
<input type="text" class="cari_keyword form-control" id="cari_jrsn_pil1_id" placeholder="ID..." />
<div id="result"></div>
</div>
<div class="row-fluid">
<div class="span12">
<div class="row-fluid">
<div class="alert alert-info">
<a name="contact"></a>
<h2>www.andeznet.com</h2>
<p class="text-info">Gudang Teknologi & Informasi</p>
<p>© www.andeznet.com&nbsp<?php echo date("Y");?></p>
</div><!--/span-->
</div><!--/row-->
</div><!--/span-->
</div><!--/row-->
</div>
<script src="assets/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
$(".cari_keyword").keyup(function()
{
var cari_keyword_value = $(this).val();
var dataString = 'cari_keyword='+ cari_keyword_value;
if(cari_keyword_value!='')
{
$.ajax({
type: "POST",
url: "cari.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
}).done(function(respuesta){
$("#nombre").val(respuesta.nombre);
});
}
return false;
});
$("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.nama_siswa').html();
var decoded = $("<div/>").html($name).text();
$('#cari_keyword_id').val(decoded);
});
$(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("cari_keyword")){
$("#result").fadeOut();
}
});
$('#cari_keyword_id').click(function(){
$("#result").fadeIn();
});
});
</script>
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
cari.php
<?php
include('koneksi.php');
if(isset($_POST['cari_keyword']))
{
$cari_keyword = $dbConnection->real_escape_string($_POST['cari_keyword']);
$sqlSiswa="SELECT id_daftar,s_nama FROM master WHERE s_nama LIKE '%$cari_keyword%'";
$resSiswa=$dbConnection->query($sqlSiswa);
if($resSiswa === false) {
trigger_error('Error: ' . $dbConnection->error, E_USER_ERROR);
}else{
$rows_returned = $resSiswa->num_rows;
}
$bold_cari_keyword = '<strong>'.$cari_keyword.'</strong>';
if($rows_returned > 0){
while($rowSiswa = $resSiswa->fetch_assoc())
{
echo '<div class="show" align="left"><span class="nama_siswa">'.str_ireplace($cari_keyword,$bold_cari_keyword,$rowSiswa['s_nama']).'</span></div>';
}
}else{
echo '<div class="show" align="left">No matching records.</div>';
}
}
?>
table.sql
CREATE TABLE IF NOT EXISTS `master` (
`id_daftar` int(5) NOT NULL,
`s_nama` varchar(150) NOT NULL,
`s_jk` int(1) NOT NULL,
`s_agama` int(1) NOT NULL,
`s_tmp_lahir` varchar(100) NOT NULL,
`s_tgl_lahir` date NOT NULL,
`jrsn_pil1` int(4) NOT NULL,
`jrsn_pil2` int(4) NOT NULL,
`tgl_daftar` date NOT NULL,
`nisn` varchar(15) NOT NULL,
`noreg` varchar(10) NOT NULL,
`Alamat` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=172 ;
INSERT INTO `master` (`id_daftar`, `s_nama`, `s_jk`, `s_agama`, `s_tmp_lahir`, `s_tgl_lahir`, `jrsn_pil1`, `jrsn_pil2`, `tgl_daftar`, `nisn`, `noreg`, `Alamat`) VALUES
(30, 'GUSTI SUMAINDRA', 1, 1, 'sadadad', '2009-03-01', 1103, 1254, '2015-04-08', '0001', '0001', ''),
(31, 'AFIF PRASETYA', 1, 0, '', '0000-00-00', 0, 0, '2015-04-08', '0002', '0002', '');
koneksi.php
<?php
define('_HOST_NAME', 'localhost');
define('_DATABASE_USER_NAME', 'root');
define('_DATABASE_PASSWORD', '');
define('_DATABASE_NAME', 'prueba');
$dbConnection = new mysqli(_HOST_NAME, _DATABASE_USER_NAME, _DATABASE_PASSWORD, _DATABASE_NAME);
if ($dbConnection->connect_error) {
trigger_error('Connection Failed: ' . $dbConnection->connect_error, E_USER_ERROR);
}
?>
You can use a data attribute for more information like this:
echo '<div class="show" align="left"><span class="nama_siswa" data-id="'.$rowSiswa['id_daftar'].'">'.str_ireplace($cari_keyword,$bold_cari_keyword,$rowSiswa['s_nama']).'</span></div>';
Now you have both the name and the id associated with the result the user clicks. You can use this to change the other input.
$("#result").live("click",function(e){
var $clicked = $(e.target);
var $clickedKeyword = $clicked.find('.nama_siswa');
var $name = $clickedKeyword.html();
var id = $clickedKeyword.data('id');
var decoded = $("<div/>").html($name).text();
$('#cari_keyword_id').val(decoded);
$('#cari_jrsn_pil1_id').val(id);
});
Hope this helps.

php session with jqmobi getting destroyed on page reload

I am trying to use jqmobi with PHP where everything is working but when I try to use PHP session it's not working. First when I use jquery post then it will retrieve data from server but when I reload page then session is destroyed.
I have kept session_start() in every file but still of no use. So if anybody have worked with jqmobi and PHP, share your experience. I am posting my main index.php file:
<?php
session_start();
?>
<!DOCTYPE html>
<!--HTML5 doctype-->
<html>
<head>
<title>UI Starter</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes" />
<META HTTP-EQUIV="Pragma" CONTENT="no-cache" >
<link rel="stylesheet" type="text/css" href="http://cdn.app-framework-software.intel.com/2.0/af.ui.base.css"/>
<link rel="stylesheet" type="text/css" href="http://cdn.app-framework-software.intel.com/2.0/icons.css" />
<link rel="stylesheet" type="text/css" href="http://cdn.app-framework-software.intel.com/2.0/af.ui.css" />
<!-- http://code.jquery.com/jquery-1.10.1.min.js -->
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="./js/lib/jquery.validate.min.js"></script>
<script src="./js/jq.appframework.js"></script>
<script src="http://cdn.app-framework-software.intel.com/2.0/appframework.ui.min.js"> </script>
<script src="./fcharts/FusionCharts/FusionCharts.js"></script>
<!-- include touch on desktop browsers only -->
<script>
// $.ui.showBackButton = false;
if (!((window.DocumentTouch && document instanceof DocumentTouch) || 'ontouchstart' in window)) {
var script = document.createElement("script");
script.src = "plugins/af.desktopBrowsers.js";
var tag = $("head").append(script);
//$.os.android = true; //let's make it run like an android device
//$.os.desktop = true;
}
</script>
</head>
<body>
<div id="afui"> <!-- this is the main container div. This way, you can have only part of your app use UI -->
<!-- this is the header div at the top -->
<div id="header">
<a onclick="$.ui.toggleSideMenu()" id="mainbuon" class="menuButton" style="float:right"></a>
</div>
<div id="content">
<!-- here is where you can add your panels -->
<div title='Management' id="elogin" class="panel" selected="true"
data-load="notloadedPanel" data-unload="notunloadedPanel">
<h2 >login</h2>
<form id="sample" style="position:absolute;width:250px;height:350px; left:50%; top:50%;margin-left:-130px;margin-top:-50px;">
<input type="email" id="email" name="email" value="" placeholder="username"style="text-align:center;" >
<div id="error"></div>
<input type="password" id="password" name="password" value="" placeholder="password" style="text-align:center;" >
<div id="error1"></div>
<a class="button" onclick="validate()" >Login</a>
</form>
<footer>
</footer>
</div>
<div title='List' data-defer="evelist.php" id="elist" class="panel" data-header="testheader"
data-tab="navbar_list" data-load="loadedPanel" data-unload="unloadedPanel">
</div>
<div id="setting" class="panel" title='Management' data-defer="Setting.php" data-load="settingloadedPanel"
data-unload="settingunloadedPanel" data-tab="navbar_list" >
</div>
<div id="missreport" class="panel" data-defer="MissReports.php" title='Management' data-load="reportloadedPanel"
data-unload="reportunloadedPanel" data-tab="navbar_list" >
</div>
<header id="testheader">
<a onclick="$.ui.toggleSideMenu()" id="mainbuon" class="menuButton" style="float:left"></a>
<!-- <a id="backButton" onclick="$.ui.goBack()" class='button'>Go Back</a> -->
<h1>Events List</h1>
</header>
</div> <!-- content ends here #smessage -->
<!-- bottom navbar. Add additional tabs here -->
<div id="navbar">
<div class="horzRule"></div>
<a href="#Dashboard" id='navbar_dash' class='icon home'>Dashboard</a>
<a href="#elist" id='navbar_list' class='icon home'>list</a>
<a href="#aevent" id='navbar_add' class='icon home'>Add ent</a>
<a href="#smessage" id='navbar_sent' class='icon home'>Sent Msg</a>
<a href="#sendmessage" id='navbar_send' class='icon home'>Send Msg</a>
</div>
<!-- this is the default left side nav menu. If you do not want any, do not include these -->
</div>
</body>
<script type="text/javascript">
var webRoot = "./";
$.ui.autoLaunch = false; //By default, it is set to true and you're app will run right away. We set it to false to show a splashscreen
$(document).ready(function(){
//
$.ui.launch();
});
$.ui.backButtonText="Back"
$(document).bind("swipeLeft",function(){
$.ui.toggleSideMenu(false);
});
$(document).bind("swipeRight",function(){
$.ui.toggleSideMenu(true);
});
//$.ui.useAjaxCacheBuster=true;
function logout(){
var rt= "<?php echo session_destroy(); ?>";
$.ui.loadContent("#elogin",false,false,"slide");
} /***login form panel start here****/
function notloadedPanel(){
$.ui.disableSideMenu();
$('#mainbuon').hide();
$.ui.clearHistory();
}
function notunloadedPanel(){
$.ui.enableSideMenu();
$('#mainbuon').show();
}
function validate(){
var validator = $("#sample").validate({
rules: {
email: {
required: true,
}
, password: {
required: true,
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "email" ) {
// error.insertAfter("#error");
error.appendTo('#error');
} else {
//error.insertAfter(element);
error.appendTo('#error1');
} },submitHandler: function() {
$.post(webRoot + 'parameter.php', {
email:$('#email').val(),password:$('#password').val(),Login:'Login'
}, function (data) {
if($.trim(data)=='success'){
$.ui.loadContent("#elist",false,false,"slide");
}else{
alert("wrong username and password");
}
});
}
});
if(validator.form()){
$('form#sample').submit();
}
}
/***login form panel ends here****/
document.addEventListener("DOMContentLoaded", init, false);
$.ui.ready(function () {
//This function will get executed when $.ui.launch has completed
// $.ui.showBackButton = false;
});
/* This code is used for native apps */
var onDeviceReady = function () {
AppMobi.device.setRotateOrientation("portrait");
AppMobi.device.setAutoRotate(false);
webRoot = AppMobi.webRoot + "/";
//hide splash screen
AppMobi.device.hideSplashScreen();
$.ui.blockPageScroll();
};
document.addEventListener("appMobi.device.ready", onDeviceReady, false);
</script>
The code should be sufficient, however you need to find out if session_destroy or unset($_SESSION) was called else where
<?php
session_start();
$_SESSION['key'] = "value";
?>

Categories