Autocomplete Textbox from Active Directory usind LDAP Users in php - php

I am trying to autocomplete a field that picks names of users from LDAP. My codes are as follows :
index.php
$(document).ready(function() {
$("#search-box").keyup(function() {
$.ajax({
type: "POST",
url: "readCountry.php",
data: 'keyword=' + $(this).val(),
beforeSend: function() {
$("#search-box").css("background", "#FFF url(LoaderIcon.gif) no-repeat 165px");
},
success: function(data) {
$("#suggesstion-box").show();
$("#suggesstion-box").html(data);
$("#search-box").css("background", "#FFF");
}
});
});
});
function selectCountry(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
body {
width: 610px;
}
.frmSearch {
border: 1px solid #F0F0F0;
background-color: #C8EEFD;
margin: 2px 0px;
padding: 40px;
}
#country-list {
float: left;
list-style: none;
margin: 0;
padding: 0;
width: 190px;
}
#country-list li {
padding: 10px;
background: #FAFAFA;
border-bottom: #F0F0F0 1px solid;
}
#country-list li:hover {
background: #F0F0F0;
}
#search-box {
padding: 10px;
border: #F0F0F0 1px solid;
}
<html>
<head>
<TITLE>jQuery AJAX Autocomplete - Country Example</TITLE>
<head>
<body>
<div class="frmSearch">
<input type="text" id="search-box" placeholder="Country Name" />
<div id="suggesstion-box"></div>
</div>
</body>
</html>
readCountry.php
<?php
if(!empty($_POST["keyword"])) {
$Name=$_POST["keyword"];
$username="********";
$password="********";
$lc = ldap_connect("********") or
die("Couldn't connect to AD!");
ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($lc,$username,$password);
$base = "OU=********,DC=********,DC=********";
$filt = "(&(&(&(objectCategory=person)(objectClass=user)(name=$Name*))))";
$sr = #ldap_search($lc, $base, $filt);
$info = ldap_get_entries($lc, $sr);
for ($i = 0; $i < $info["count"]; $i++) {
$info[$i]["cn"][0] ;
}
if ($i == 0) {
echo "No matches found!";
}
if(!empty($info[$i]["cn"][0])) {
?>
<ul id="country-list">
<?php
foreach($info[$i]["cn"][0] as $country) {
?>
<li onClick="selectCountry('<?php echo $country ?>');"><?php echo $country ?></li>
<?php } ?>
</ul>
<?php } } ?>
What I have :
This isn't returning names from LDAP nor is there any error that is dispalyed for me to fix it.
What I need :
When A is typed, all the names starting with 'A' should be shown in the dropdown.
Appreciate any help :) Thanks in advance! :)

$('#search').keyup(function () {
var data = this.value.split(" ");
var rows = $("#table tbody tr").hide();
if(this.value ===""){
rows.show();
return;
}
rows.hide();
rows.filter(function(i,v){
var t = $(this);
for (var d = 0; d < data.length; d++) {
if (t.is(":Contains('" + data[d] + "')")) {
return true;
}
}
return false;
}).show();
});

I found a way out! Just had to change the onclick in readcountry.php as shown below :
<?php
if(!empty($_POST["keyword"])) {
$Name=$_POST["keyword"];
$username="********";
$password="********";
$lc = ldap_connect("********") or
die("Couldn't connect to AD!");
ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($lc,$username,$password);
$base = "OU=********,DC=********,DC=********";
$filt = "(&(&(&(objectCategory=person)(objectClass=user)(name=$Name*))))";
$sr = #ldap_search($lc, $base, $filt);
$info = ldap_get_entries($lc, $sr);
for ($i = 0; $i < $info["count"]; $i++) {
<li onClick="selectCountry('<?php echo $info[$i]["cn"][0] ?>');"><?php echo $info[$i]["cn"][0] ?></li>
}
if ($i == 0) {
echo "No matches found!";
} }

Related

Display image after upload to a folder into PDF using PHP

I can upload the image to a new folder, but the main things is need to display it out from that folder to PDF. Then I am using FDPF, but then I get an error message when displaying:
"Uncaught Exception: FPDF error: Can't open image file: Tulips.jpg "
But when i echo the $img it display. Then i add on $img in pdf->Image($img) it wont work it appear above message error.
Here is what I have try to code htmltopdf.html
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function ValidateSingleInput(oInput) {
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
oInput.value = "";
return false;
}
}
}
return true;
}
function handleFileSelect(event)
{
console.log(event)
var input = this;
if (input.files)
{
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++)
{
var reader = new FileReader();
console.log(reader)
reader.onload = (function (e)
{
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="',e.target.result, '" title="', escape(e.name), '"/><span class="remove_img_preview"></span>'].join('');
document.getElementById('preview').insertBefore(span, null);
});
reader.readAsDataURL(input.files[i]);
}
}
}
$(document).ready(function(){
// Listen to click event on the submit button
$('#submit').click(function (e) {
e.preventDefault();
var myform = document.getElementById("form");
var fd = new FormData(myform);
$.ajax({
url:"upload1.php",
type:"POST",
data:fd,
//dataType: 'json',
processData: false,
contentType: false,
cache: false,
success:function(data){
alert("Success Insert!");
},
});
});
$('#fileToUpload').change(handleFileSelect);
//preview image and remove
$('#preview').on('click', '.remove_img_preview',function ()
{
$(this).parent('span').remove();
$("#fileToUpload").val("");
});
});
</script>
<style>
div.relative {
position: relative;
top: -300px;
}
#bottom{
position: relative;
right: 0;
bottom: 0;
}
.thumb
{
width: 100px;
height: 100px;
margin: 0.2em -0.7em 0 0;
}
.remove_img_preview
{
position:relative;
top:-25px;
right:5px;
background:black;
color:white;
border-radius:50px;
font-size:0.9em;
padding: 0 0.3em 0;
text-align:center;
cursor:pointer;
}
.remove_img_preview:before
{
content: "Ă—";
}
table,th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
textarea {
width: 100%;
height: 300px;
padding: 12px 20px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
background-color: #f8f8f8;
font-size: 16px;
resize:none;
}
table.menu {
border: 1px solid black;
border-collapse: collapse;
width: 10%;
float:right;
}
</style>
<body>
<form action="generate_pdf.php" method="POST" id="form">
<input type="submit" value="Send" id="submit" name="submit"><input type="reset" value="Clear">
<input type="file" name="fileToUpload[]" id="fileToUpload" onchange="ValidateSingleInput(this);" multiple = "multiple" style="display: none;">
<input type="button" value="Browse..." onclick="document.getElementById('fileToUpload').click();" />
<input type="submit" value="PDF">
<div id="preview"></div>
</form>
</body>
</html>
Here is the upload1.php
<?php
require 'config.php';
$year = date("yy");
$year = substr($year, -2);
$month = date("m");
$key = "KM".$year.$month;
$total = count($_FILES['fileToUpload']['name']);
$sql = "SELECT * FROM images WHERE id LIKE '$key%' ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
//GET NEW RUNNING NUMBER BY CHECKING DATABASE
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$number = sprintf('%03d',substr($row['id'], -3)+ 1) ;
$ans = $key.$number;
}
}
else
{
$ans = $key."001";
}
$target_dir = "D:/XAMPP/htdocs/new3/new3/uploads/" . $ans;
if(!file_exists($target_dir))
{
mkdir($target_dir,0777,true);
}
$sql = $conn->query ("INSERT INTO images (id) VALUES ('$ans')");
$allowed = array('gif', 'png', 'jpg','xlsx','pdf','doc');
$ext = pathinfo($total, PATHINFO_EXTENSION);
if (!in_array($ext, $allowed)) {
echo 'error';
}
for( $i=0 ; $i < $total ; $i++ )
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$i], $target_dir."/".$ans."-".$_FILES["fileToUpload"]["name"][$i]))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"][$i]). " has been uploaded."."<br>";
}
else
{
echo "Sorry, there was an error uploading your file.";
}
}
?>
Here is the generate_pdf.php that i have try:
<?php
$img=$_FILES["fileToUpload"]["name"][0];
echo $img;
require 'fpdf181/fpdf.php';
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',10);
$pdf->Image($img,NULL,NULL,0,0,'PNG');
$pdf->Output();
?>
I don't know whether I wrote it correctly or not? Or just need to call back the path where image is stored and display it out? Myself already brainstorming, don't know how it works. Can anyone help? Maybe this is a duplicate questions but I can't even find any related things, just can found how to retrieve from database.
First problem is that your <form> tag is missing the enctype="multipart/form-data" attribute.
As for the PHP error, $_FILES["fileToUpload"] is an array, so $image=$_FILES["fileToUpload"]["name"] should change to $_FILES["fileToUpload"]["name"][0] (assuming you want the first file). So generate_pdf.php should start with:
$image=$_FILES["fileToUpload"]["name"][0];
After i have amend some of it the error come out is "Fatal error: Uncaught Exception: FPDF error: Can't open image file"
This is the code file i have amend call generate_pdf.php
$image=$_FILES["fileToUpload"]["name"][0];
$img="C:/xampp/htdocs/test/uploads/".$image;
require 'fpdf181/fpdf.php';
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',10);
$pdf->Image($img, NULL, NULL, 0, 0, 'png');
$pdf->Output();

Unable to get lazy load data in codeigniter using AJAX

I am doing an e-commerce website. Just want to implement lazy load. I can fetch the data at first load but again if I scroll down no data can be fetched.
**HTML CODE**
<div class="row" id="fetchedprodducts">
<div class="row" id="load_data_message"></div>
<div id="load_data"></div>
</div>
**CSS**
#-webkit-keyframes placeHolderShimmer {
0% {
background-position: -468px 0;
}
100% {
background-position: 468px 0;
}
}
#keyframes placeHolderShimmer {
0% {
background-position: -468px 0;
}
100% {
background-position: 468px 0;
}
}
.content-placeholder {
display: inline-block;
-webkit-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
-webkit-animation-name: placeHolderShimmer;
animation-name: placeHolderShimmer;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
background: #f6f7f8;
background: -webkit-gradient(linear, left top, right top, color-stop(8%, #eeeeee), color-stop(18%, #dddddd), color-stop(33%, #eeeeee));
background: -webkit-linear-gradient(left, #eeeeee 8%, #dddddd 18%, #eeeeee 33%);
background: linear-gradient(to right, #eeeeee 8%, #dddddd 18%, #eeeeee 33%);
-webkit-background-size: 800px 104px;
background-size: 800px 104px;
height: inherit;
position: relative;
}
.post_data
{
padding:24px;
border:1px solid #f9f9f9;
border-radius: 5px;
margin-bottom: 24px;
box-shadow: 0px 0px 5px #eeeeee;
}
**AJAX**
<script>
$(document).ready(function(){
var url = window.location.href;
var idx = url.indexOf("product");
var slugx = url.indexOf("product");
var slug = url.substring(idx).split("/")[1];
var line = url.substring(slugx).split("/")[2];
var limit = 8;
var start = 0;
var action = 'inactive';
function lazy_load(limit){
var output = '';
for(var count = 0; count < limit; count++)
{
output += '<div class="post_data col-md-4 col-12">';
output += '<p><span class="content-placeholder" style="width:90%; height: 30px;"> </span></p>';
output += '<p><span class="content-placeholder" style="width:90%; height: 80px;"> </span></p>';
output += '</div>';
}
$('#load_data_msg').html(output);
}
lazy_load(limit,slug,line);
function load_data(limit,start,slug,line)
{
$.ajax({
url:BASE_URL+'front/Products/fetch',
method:"POST",
data:{limit:limit,start:start,slug:slug,line:line},
cache: false,
success:function(data)
{
if(data == '')
{
$('load_data_msg').html('<h3> No Product is available </h3>');
}
else{
$('#fetchedprodducts').append(data);
$('#load_data_msg').html("");
action = 'inactive';
}
}
});
}
if(action == 'inactive')
{
action = 'active';
load_data(limit, start,line,slug);
}
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
{
lazy_load(limit);
action = 'active';
start = start + limit;
setTimeout(function(){
load_data(limit, start);
}, 1000);
}
});
});
</script>
**Controller**
public function fetch(){
$output ='';
$limit = $this->input->post('limit');
$start = $this->input->post('start');
$line = $this->input->post('line');
$slug = $this->input->post('slug');
$data = $this->Userfront_model->fetch_data($limit,$start ,$line,$slug);
if($data->num_rows() > 0){
foreach($data->result() as $row)
{
$output .= "<div class='post_data col-md-3 col-6'>
<a class='all-link--pro' href='" . site_url('product_view/' . $row->id . "/" . $row->slug ) . "'>
<img style='box-shadow: 0px 0px 22px 0px #616161' class='img-fluid img-size' src='" . base_url('assets/img/posts/' . $row->main_img) . " '>
<p>" . $row->title . "</p>
<p> <b>" . $row->uniquecode. "</b> </p>
<p>Rs " . $row->price. "</p>
</a>
</div>";
}
}
echo $output;
}
MODEL
function fetch_data($limit, $start,$line,$slug)
{
$this->db->order_by('cv_products.id', 'DESC');
$this->db->select('cv_products.*, cv_category.name as categoryname,product_line.id as lineid, product_line.name as linename,cv_category.id as category_id,delivery_time.id as deliverid, delivery_time.name as timingname' );
$this->db->join('cv_category','cv_category.id = cv_products.category', 'left');
$this->db->join('product_line','product_line.id = cv_products.product_line', 'left');
$this->db->join('delivery_time','delivery_time.id = cv_products.timing', 'left');
$this->db->from('cv_products');
$this->db->where('cv_products.product_line' , $line);
$this->db->where('product_line.slug' , $slug);
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query;
}
I am able to fetch the first 8 products but unable to get the rest of the products while scrolling.
NOTE:
if i remove the where clause from model it work perfectly
You haven't passed the values line and slug to the function call load_data inside scroll method.
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
{
lazy_load(limit);
action = 'active';
start = start + limit;
setTimeout(function(){
load_data(limit, start, line, slug); // pass missing parameters here
}, 1000);
}
});

Input sends empty message

I'm making live chatter for my project, and I need this script to recognize this:
If clientmsg is empty, it will call out an error and won't post the
message.
If clientmsg has more than 3 or 4 chars (letters) - it will post the message.
The code:
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post3.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
I can't find out how this works.
Here you can see the whole code for it.
index.php
<?php
/*****************************
File: index.php
Written by: exZerry development crew
******************************/
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "";
} else {
header ("Location: login.php");
}
require('includes/config.php');
echo $sOutput;
if(isset($_POST['enter'])){
if($_POST['username'] != ""){
$_SESSION['username'] = stripslashes(htmlspecialchars($_POST['username']));
}
else{
echo '<span class="error">Please type in a name</span>';
}
}
?>
<style type="text/css">
input {
font: 12px;
}
.loginbox {
background-image: url(bar.png);
width: 100%;
height: 100%;
margin-top: -38;
}
#loginform {
font:16px dinpro;
color: #ffffff;
margin-top: 100;
}
#hedthe {
background-image: url(spacer.png);
font-family: bank-gt, sans-serif;
font-size: 34;
width: 830;
height: 34;
font-weight: normal;
}
#thereis {
magrin-top: -20;
}
#chatbox {
text-align: justify;
height: 70%;
width: 100%;
overflow: auto;
opacity: 0.91;
}
#usermsg {
width: 100%;
font-family: Play, sans-serif;
font-size: 14;
font-weight: normal;
color: #ffffff;
border: 0px solid black;
text-indent: 5px;
height: 32;
margin-top: 5px;
border: 0px solid black;
color: #ffffff;
background-image: url(chatinp.png);
}
input {
opacity: 0.7;
}
#submitmsg {
background-color: #48513e;
width: 0;
height: 0;
font-size: 20;
font-weight: normal;
color: #ffffff;
text-align: left;
border: 0px solid black;
}
.error {
color: #000000;
}
#menu {
margin-right: 0;
}
.welcome {
float:left;
}
.logout {
float:right;
}
.msgln {
margin-right: 0;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="modules/chatbox.js"></script>
<!-- Actual chat -->
<div id="chatbox">
<?php
if(file_exists("tmp/log.html") && filesize("tmp/log.html") > 0){
$handle = fopen("tmp/log.html", "r");
$contents = fread($handle, filesize("tmp/log.html"));
fclose($handle);
echo $contents;
}
?>
</div>
<form name="message" action="" id="sender" class="sender">
<input name="usermsg" id="usermsg" class="required" type="text" placeholder="Your message here" maxlength="60"/>
<input name="submitmsg" type="submit" id="submitmsg" width="0" height="0"/>
</form>
chatbox.js file
// jQuery Document
$(document).ready(function(){
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post3.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
//Load the file containing the chat log
function loadLog(){
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url: "tmp/log.html",
cache: false,
success: function(html){
$("#chatbox").html(html); //Insert chat log into the #chatbox div
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
},
});
}
setInterval (loadLog, 2000); //Reload file every 3 seconds
});
post3.php file
<?
session_start();
if(isset($_SESSION['username'])){
$text = $_POST['text'];
$fp = fopen("tmp/log.html", 'a');
fwrite($fp, "<div class='msgln'> <b>".$_SESSION['username']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
This is full js + php chatter.
Like this?
$("#submitmsg").click(function(){
var clientmsg = $.trim($("#usermsg").val());
if(clientmsg.length >= 3){
$.post("post3.php", {text: clientmsg});
$("#usermsg").val("");
}else{
alert('error');
}
return false;
});
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
// check if the length of the string is greater than 3 letters
if(clientmsg.length > 3)
$.post("post3.php", {text: clientmsg});
else
alert("Error");
$("#usermsg").attr("value", "");
return false;
});

php events calendar. The javascript button wont press

I have been following a very annoying tutorial on how to make a php calender. I have got to the final bit but where i have a button to display the information from the database on certain dates when i click it nothing happens. It is supposed to bring up a box displaying the information. There is no error message or anything just nothing happens when you click it. Maybe ive made a simple mistake? Does anyone have any ideas? I need to finish this tonight :(
Thanks
events.php
<?php
$deets = $_POST['deets'];
$deets = preg_replace('#[^0-9/]#i', '', $deets);
include ("connect.php");
$events = '';
$query = mysql_query('SELECT description FROM events WHERE evdate = "'.$deets.'"');
$num_rows = mysql_num_rows($query);
if($num_rows > 0) {
$events .= '<div id="eventsControl"><button onMouseDown="overlay()">Close</button><br /><br /><b> ' . $deets . '</b><br /><br /></div>';
while($row = mysql_fetch_array($query)){
$desc = $row['description'];
$events .= '<div id="eventsBody">'. $desc . '<br /><hr><br / ></div>';
}
}
echo $events;
?>
connect.php
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "heyman";
$db_name = "ecalandar";
$conn = mysql_connect("$db_host", "$db_username","$db_pass") or die ("could not connect
to mysql");
mysql_select_db("$db_name") or die ("no database");
?>
calCSS.css
#calendar_wrap {
width: 924px;
margin-left: auto;
margin-right: auto;
overflow: hidden;
}
.title_bar {
width: 100%;
height: 30px;
}
.previous_month {
float: left;
width: 308px;
height: 30px;
text-align: left;
}
.show_month {
float: left;
width: 308px;
height: 30px;
text-align: center;
}
.next_month {
float: left;
width: 308px;
height: 30px;
text-align: right;
}
.week_days {
width: 100%;
}
.days_of_the_week {
float: left;
width: 14%;
text-align: center;
}
.cal_day {
position: relative;
float: left;
margin-right: 4px;
margin-bottom: 4px;
width: 128px;
height: 95px;
background-color: #9C9;
}
.day_heading {
position: relative;
float: left;
width: 40px;
height: 16px;
padding: 6px;
color: #000;
font-family: Arial;
font-size: 14px;
}
.openings {
width: 100%;
clear:left;
text-align: center;
}
.non_cal_day {
position: relative;
float: left;
margin-right: 4px;
margin-bottom: 4px;
width: 128px;
height: 95px;
background-color: #CCC;
}
.clear {
clear: both;
}
<!-- overlay --!>
body {
height:100%;
margin:0;
padding:0;
}
#overlay {
display: none;
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 2000;
background: #000;
opacity: .9;
}
#events {
display: none;
width:500px;
border:4px solid #9C9;
padding:15px;
z-index: 3000;
margin-top: 100px;
margin-right: auto;
margin-left: auto;
background-color: #FFF;
height: 400px;
overflow: scroll;
}
#eventControl {
display: none;
width: 100%;
height:30px;
z-index: 3000;
}
#eventBody {
display: none;
width: 100%;
z-index: 3000;
}
calendar_start.php
<?php
$showmonth = $_POST['showmonth'];
$showyear = $_POST['showyear'];
$showmonth = preg_replace('#[^0-9]#i', '', $showmonth);
$showyear = preg_replace('#[^0-9]#i', '', $showyear);
$day_count = cal_days_in_month(CAL_GREGORIAN, $showmonth, $showyear);
$pre_days = date('w', mktime(0,0,0, $showmonth, 1, $showyear));
$post_days = (6 - (date('w', mktime(0,0,0, $showmonth, $day_count,$showyear))));
echo '<div id="calendar_wrap">';
echo '<div class="title_bar">';
echo '<div class="previous_month"><input name="myBtn" type="submit" value="Previous
Month" onClick="javascript:last_month();"></div>';
echo '<div class="show_month">' . $showmonth . '/' . $showyear . '</div>';
echo '<div class="next_month"><input name="myBtn" type="submit" value="Next Month"
onClick="javascript:next_month();"></div>';
echo '</div>';
echo '<div class="week_days">';
echo '<div class="days_of_the_week">Mon</div>';
echo '<div class="days_of_the_week">Tue</div>';
echo '<div class="days_of_the_week">Wed</div>';
echo '<div class="days_of_the_week">Thur</div>';
echo '<div class="days_of_the_week">Fri</div>';
echo '<div class="days_of_the_week">Sat</div>';
echo '<div class="days_of_the_week">Sun</div>';
echo '<div class="clear"></div>';
echo '</div>';
/* Previous Month Filler Days */
if ($pre_days != 0) {
for($i = 1 ; $i<=$pre_days;$i++) {
echo '<div class="non_cal_day"></div>';
}
}
/* Current Month */
//connect to mysql
include ("connect.php");
//
for($i=1; $i<= $day_count; $i++) {
//get events logic
$date = $showmonth.'/'.$i.'/'.$showyear;
$query = mysql_query('SELECT id FROM events WHERE evdate = "'.$date.'"');
$num_rows = mysql_num_rows($query);
if($num_rows > 0) {
$event = "<input name = '$date' type = 'submit' value='Details' id='$date' onClick =
'javascript:show_details(this);'>";
}
//end get events
echo '<div class="cal_day">';
echo '<div class="day_heading">' . $i . '</div>';
//show events button
if($num_rows != 0) { echo "<div class='openings'><br />".$event."</div>";
}
//end button
echo '</div>';
}
/* Next Month Filler Days */
if ($post_days != 0) {
for ($i=1; $i<=$post_days; $i++) {
echo '<div class="non_cal_day"></div>';
}
}
echo '</div>';
?>
show_calendar.php
<!DOCTYPE html>
<html>
<head>
<link href="calCss.css" rel="stylesheet" type="text/css" media="all" />
<script language="JavaScript" type="text/javascript">
function initialCalendar(){
var hr = new XMLHttpRequest();
var url = "calendar_start.php";
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var year = currentTime.getFullYear();
showmonth = month;
showyear = year;
var vars = "showmonth="+showmonth+"&showyear="+showyear;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("showCalendar").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("showCalendar").innerHTML = "processing...";
}
</script>
<script language="JavaScript" type="text/javascript">
function next_month(){
var nextmonth = showmonth + 1;
if (nextmonth > 12) {
nextmonth = 1;
showyear = showyear + 1;
}
showmonth = nextmonth;
var hr = new XMLHttpRequest();
var url = "calendar_start.php";
var vars = "showmonth="+showmonth+"&showyear="+showyear;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("showCalendar").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("showCalendar").innerHTML = "processing...";
}
</script>
<script language="JavaScript" type="text/javascript">
function last_month(){
var lastmonth = showmonth - 1;
if (lastmonth < 1) {
lastmonth = 12;
showyear = showyear - 1;
}
showmonth = lastmonth;
var hr = new XMLHttpRequest();
var url = "calendar_start.php";
var vars = "showmonth="+showmonth+"&showyear="+showyear;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("showCalendar").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("showCalendar").innerHTML = "processing...";
}
</script>
<script type="text/javascrip">
function overlay() {
el = document.getElementById("overlay");
el.style.display = (el.style.display == "block") ? "none" : "block";
el = document.getElementById("events");
el.style.display = (el.style.display == "block") ? "none" : "block";
el = document.getElementById("eventsBody");
el.style.display = (el.style.display == "block") ? "none" : "block";
}
</script>
<script language="JavaScript" type="text/javascript">
function show_details(theId){
var deets = (theId);
el = document.getElementById("overlay");
el.style.display = (el.style.display == "block") ? "none" : "block";
el = document.getElementById("events");
el.style.display = (el.style.display == "block") ? "none" : "block";
var hr = new XMLHttpRequest();
var url = "events.php";
var vars = "deets="+deets;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState ==4 && hr.status == 200 {
var return_data = hr.responseText;
document.getElementById("events").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("events").innerHTML = "processing...";
}
</script>
</head>
<body onLoad="initialCalendar();">
<div id="showCalendar"></div>
<div id="overlay"></div>
<div id="events"></div>
</div>
</body>
</html>
without looking too closely at your code i noticed you are passing strings to your (outdated and dangerous) mysql functions
$db_host = "localhost";
$db_username = "root";
$db_pass = "heyman";
$db_name = "ecalandar";
$conn = mysql_connect($db_host, $db_username,$db_pass) or die ("could not connect to mysql");
mysql_select_db($db_name) or die ("no database");
you should do some reading on pdo/mysqli

Upload progress bar using php and jquery

So im trying to have an upload with a progress bar, i installed uploadprogress pecl, and the upload worked perfectly if the action in the form leads to upload.php, any other name, and it stops working.
If the name is not upload.php the output is simply "100" (which can be seen why below with the getprogress.php file)
this is the form: (this versions works, as the file is upload.php)
<form method="post" action="/test/upload.php" enctype="multipart/form-data" id="upload-form" target="upload-frame">
<input type="hidden" id="uid" name="UPLOAD_IDENTIFIER" value="<?php echo $uid; ?>">
<input type="file" name="file">
<input type="submit" name="submit" value="Upload!">
</form>
</div>
<div style="float:left;width:100%;">
<div id="progress-bar"></div>
</div>
<iframe id="upload-frame" name="upload-frame"></iframe>
this is the jquery:
<script>
(function ($) {
var pbar;
var started = false;
$(function () {
$('#upload-form').submit(function() {
pbar = $('#progress-bar');
pbar.show().progressbar();
$('#upload-frame').load(function () {
started = true;
});
setTimeout(function () {
updateProgress($('#uid').val());
}, 1000);
});
});
function updateProgress(id) {
var time = new Date().getTime();
$.get('../uploadprogress/getprogress.php', { uid: id, t: time }, function (data) {
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
started = progress < 100;
updateProgress(id);
}
started && pbar.progressbar('value', progress);
});
}
}(jQuery));
</script>
this is the file getprogress.php
<?php
if (isset($_GET['uid'])) {
// Fetch the upload progress data
$status = uploadprogress_get_info($_GET['uid']);
if ($status) {
// Calculate the current percentage
echo round($status['bytes_uploaded']/$status['bytes_total']*100, 1);
}
else {
// If there is no data, assume it's done
echo 100;
}
}
?>
ive spent about 5 hours on this trying to figure out why, and i cant. help would be greatly appreciated.
You can use this class, without using jquery:
<?php
/**
* Progress bar for a lengthy PHP process
* http://spidgorny.blogspot.com/2012/02/progress-bar-for-lengthy-php-process.html
*/
class ProgressBar {
var $percentDone = 0;
var $pbid;
var $pbarid;
var $tbarid;
var $textid;
var $decimals = 1;
function __construct($percentDone = 0) {
$this->pbid = 'pb';
$this->pbarid = 'progress-bar';
$this->tbarid = 'transparent-bar';
$this->textid = 'pb_text';
$this->percentDone = $percentDone;
}
function render() {
//print ($GLOBALS['CONTENT']);
//$GLOBALS['CONTENT'] = '';
print($this->getContent());
$this->flush();
//$this->setProgressBarProgress(0);
}
function getContent() {
$this->percentDone = floatval($this->percentDone);
$percentDone = number_format($this->percentDone, $this->decimals, '.', '') .'%';
$content .= '<div id="'.$this->pbid.'" class="pb_container">
<div id="'.$this->textid.'" class="'.$this->textid.'">'.$percentDone.'</div>
<div class="pb_bar">
<div id="'.$this->pbarid.'" class="pb_before"
style="width: '.$percentDone.';"></div>
<div id="'.$this->tbarid.'" class="pb_after"></div>
</div>
<br style="height: 1px; font-size: 1px;"/>
</div>
<style>
.pb_container {
position: relative;
}
.pb_bar {
width: 100%;
height: 1.3em;
border: 1px solid silver;
-moz-border-radius-topleft: 5px;
-moz-border-radius-topright: 5px;
-moz-border-radius-bottomleft: 5px;
-moz-border-radius-bottomright: 5px;
-webkit-border-top-left-radius: 5px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-left-radius: 5px;
-webkit-border-bottom-right-radius: 5px;
}
.pb_before {
float: left;
height: 1.3em;
background-color: #43b6df;
-moz-border-radius-topleft: 5px;
-moz-border-radius-bottomleft: 5px;
-webkit-border-top-left-radius: 5px;
-webkit-border-bottom-left-radius: 5px;
}
.pb_after {
float: left;
background-color: #FEFEFE;
-moz-border-radius-topright: 5px;
-moz-border-radius-bottomright: 5px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 5px;
}
.pb_text {
padding-top: 0.1em;
position: absolute;
left: 48%;
}
</style>'."\r\n";
return $content;
}
function setProgressBarProgress($percentDone, $text = '') {
$this->percentDone = $percentDone;
$text = $text ? $text : number_format($this->percentDone, $this->decimals, '.', '').'%';
print('
<script type="text/javascript">
if (document.getElementById("'.$this->pbarid.'")) {
document.getElementById("'.$this->pbarid.'").style.width = "'.$percentDone.'%";');
if ($percentDone == 100) {
print('document.getElementById("'.$this->pbid.'").style.display = "none";');
} else {
print('document.getElementById("'.$this->tbarid.'").style.width = "'.(100-$percentDone).'%";');
}
if ($text) {
print('document.getElementById("'.$this->textid.'").innerHTML = "'.htmlspecialchars($text).'";');
}
print('}</script>'."\n");
$this->flush();
}
function flush() {
print str_pad('', intval(ini_get('output_buffering')))."\n";
//ob_end_flush();
flush();
}
}
echo 'Starting…<br />';
$p = new ProgressBar();
echo '<div style="width: 300px;">';
$p->render();
echo '</div>';
for ($i = 0; $i < ($size = 100); $i++) {
$p->setProgressBarProgress($i*100/$size);
usleep(1000000*0.1);
}
$p->setProgressBarProgress(100);
echo 'Done.<br />';
?>
You can call the setProgressBarProgress function inside a while process, depending on your needs!!! It's great!.

Categories