Unable to get lazy load data in codeigniter using AJAX - php

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

Related

Multiple photos and text via ajax in php

I edit multiple image upload scripts.
I added the features of uploading up to 3 photos and not uploading files larger than 5mb. It works successfully.
-- But I couldn't figure out how to define the text fields I added on js and how to send it to php document with post action.
Could you help?
I am posting the codes below.
php code:
<?php
$dts = $_POST['dts'];
$ttt = explode(',',$dts);
$others_image_last='';
$image_link="/upload_img/"; //folder name
for($i=0; $i<sizeof($_FILES['upload_files']['name']); $i++) {
if (in_array($i+1, $ttt)){}else{
$new_file = md5(microtime());
$image_type = $_FILES["upload_files"]["type"][$i];
$image_name = $_FILES["upload_files"]["name"][$i];
$image_error = $_FILES["upload_files"]["error"][$i];
$image_temp_name = $_FILES["upload_files"]["tmp_name"][$i];
print_r($image_temp_name);
if (($image_type == "image/jpeg") || ($image_type == "image/png") || ($image_type == "image/pjpeg") || ($image_type == "image/jpg")) {
$test = explode('.', $image_name);
$name = $new_file.'.'.end($test);
$url = '.'.$image_link. $name;
$info = getimagesize($image_temp_name);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($image_temp_name);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($image_temp_name);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($image_temp_name);
imagejpeg($image,$url,80);
}
echo $name;
/****** insert query here ******/
}
}?>
Html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>Multiple Photo Upload</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<style>
.suggested-posts-article{
background: white;
-moz-box-shadow: rgba(0,0,0,0.0666) 0 3px 10px;
-webkit-box-shadow: rgba(0,0,0,0.0666) 0 3px 10px;
box-shadow: rgba(0,0,0,0.0666) 0 3px 10px;
display: inline-block;
margin: 5px;
width: 23%;
}
article, aside, details, figcaption, figure, footer, header, main, nav, section {
display: block;
}
article, aside, footer, header, hgroup, main, nav, section {
display: block;
}
.suggested-posts-articlees {
display: inline-block;
width: 49.5%;
}
#media screen and (max-width:450px) {
.suggested-posts-article {
width:40% !important;
}
}
.more-photos:after{ right: 3px !important;
bottom: 0px !important;}
article, aside, details, figcaption, figure, footer, header, main, nav, section {
display: block;
}
.posts_article {
background-color: #333;
background-position: 50%;
background-size: cover;
margin-bottom: 2px;
padding-bottom: 63.5%;
}
#media screen and (max-width:450px) {
.suggested-posts-article {
width:40% !important;
}
}
.more-photos:after{ right: 3px !important;
bottom: 0px !important;}
.more-photos{
cursor:pointer !important;
}
.bluess {
width:100%;
margin:10px;
}
.btn-group-sm>.btn, .btn-sm {
padding: .25rem .5rem;
font-size: .875rem;
line-height: 1.5;
border-radius: .2rem;
}
.btn-outline-secondary {
color: #868e96;
background-color: transparent;
background-image: none;
border-color: #868e96;
}
.btnxc {
display: inline-block;
padding: .5rem .75rem;
border:1px solid #868e96;
margin:3px;
padding: .25rem .5rem;
font-size: .875rem;
line-height: 1.5;
border-radius: .2rem;
color:#868e96;
}
.rrrr{
color:red;
fill:red;
}
.rrrr2{
background-color: red;
}
.datepost{
margin-top:-15px;
}
.anther_ma
{
margin:1px;
}
.set_process
{
margin: 0px 7px 0px 0px;
}
.messaf{display:none;}
.progress{
width:80%;
}
.success_msg{
color:green;
display:none;
}
#post_send{
margin:8px 0 8px 0;
}
.fa_p{
margin-right:20px;
margin-top:10px;
border:0px;
z-index:9999
}
.p_run_div{
margin-top:-7px;
border-radius:0px;
padding:0px;
margin-bottom:8px;
display:none;
}
.btnxc{
margin-left:15px;
cursor:pointer;
}
.btnxc_r{
margin-left:15px;
display:none;
}
</style>
<div class="container">
<div class="row">
<div class="col-md-8">
<h2>Multiple Photo Upload</h2>
<div class="form-group">
<label for="examplename">Name</label>
<input type="text" class="form-control" id="examplename" placeholder="First Name">
</div>
<div class="form-group">
<label for="examplesurname">First Name</label>
<input type="text" class="form-control" id="examplesurname" placeholder="Last Name">
</div>
<div><button class="imgbuts btn btn-success" style='float:left'>Choose Photo...</button> <div id="uyari" style='float:left'>You can upload 3 photos.<br>
Each photo should not be larger than 5 mb.</b></div></div>
<div style="clear:both"></div>
<form action="method" name="upload-file" class="main_form" id="form-upload-file" enctype="multipart/form-data">
<div class="ui-block">
<aside class="suggested-posts">
<div class="suggested-posts-container">
<div class="row" id="message_box"></div>
</div>
</aside>
</div>
</form>
<button class="btn btn-primary btn-md-2 " id='post_send' onclick="save_muliple_image()">Upload</button>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width:0%">
<span class="sr-only">0</span>
</div>
</div>
<h2 class="success_msg">Photo upload completed.</h2>
</div>
</div>
</div>
<script>
var xp = 0;
var input_btn = 0;
var dts = [];
$(document).on("click", ".imgbuts", function (e) {
if(xp < 3){
input_btn++;
$("#form-upload-file").append(
"<input type='file' style='display:none;' name='upload_files[]' id='filenumber" +
input_btn +
"' class='img_file upload_files' accept='.gif,.jpg,.jpeg,.png,' multiple/>"
);
$("#filenumber" + input_btn).click();
} else {
uyari.innerHTML = ' You can upload up to 3 photos.';
}
});
$(document).on("change", ".upload_files", function (e){
files = e.target.files;
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
xp++;
var f = files[i];
var boyut = f.size;
var res_ext = files[i].name.split(".");
var img_or_video = res_ext[res_ext.length - 1];
var fileReader = new FileReader();
var yuvarlama = (boyut / (1024*1024)).toFixed(2) + ' mb';
uyari.innerHTML = '';
if (boyut > 5000000) {uyari.innerHTML = ' File size larger than 5mb'; xp--; return;}
fileReader.name = f.name;
fileReader.onload = function (e) {
var file = e.target;
$("#message_box").append(
"<article class='suggested-posts-article remove_artical" +
xp +
"' data-file='" +
file.name +
"'><div class='posts_article background_v" +
xp +
"' style='background-image: url(" +
e.target.result +
")'></div><div class='p_run_div'><span class='pp_run progress_run" +
xp +
"' style='opacity: 1;'></span></div><p class='fa_p p_for_fa" +
xp +
"'><span class='cancel_mutile_image btnxc cancel_fa" +
xp +
"' deltsid='"+0+"'><b>✖ SİL</b></span><span class='btnxc btnxc_r' >✔</span><span style='float:right'>"+ yuvarlama +"</span></p></article>"
);
};
fileReader.readAsDataURL(f);
}
});
function save_muliple_image() {
suggested = $(".suggested-posts-article").length;
if (suggested > 0) {
$(".cancel_mutile_image").prop("disabled", true);
$("#post_send").prop("disabled", true);
var formData = new FormData(document.getElementById("form-upload-file"));
formData.append("dts", dts);
var xhr = new window.XMLHttpRequest();
$.ajax({
url: 'upload_ajax.php',
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function (data) {
$(".main-content").find(".message-loading-overlay2").remove();
},
error: function (e) {
$("#preview_file_div ul").html(
"<li class='text-danger'>Something wrong! Please try again.</li>"
);
},
xhr: function (e) {
xhr.upload.addEventListener(
"progress",
function (e) {
console.log(e);
if (e.lengthComputable) {
var percentComplete = ((e.loaded || e.position) * 100) / e.total;
if(percentComplete==100){
$(".progress-bar").width(percentComplete + "%").html('99' + "%");
}else{
var yuzde = Math.floor(percentComplete);
$(".progress-bar").width(percentComplete + "%").html(yuzde + "%"); }
}
},
false
);
xhr.addEventListener("load", function (e) {
$('.progress-bar').css("background","#5cb85c").html('100' + "%");
$(".btnxc_r").show();
$(".success_msg").show();
$(".cancel_mutile_image").remove();
});
return xhr;
},
});
} else {
$(".messaf").show();
}
}
var rty=0;
$(document).on("click", ".cancel_mutile_image", function (e) {
$('.cancel_mutile_image').each(function(){
chk_id = $(this).attr('deltsid');
if(chk_id==0){ rty++; $(this).attr('deltsid',rty); }
});
deltsid = $(this).attr('deltsid');
dts.push(deltsid);
$(this).parents(".suggested-posts-article").remove();
xp--;
});
</script>
</body>
</html>
Uploading multiple files in php can be tricky but the trick you need to use here is that instead of using name="upload" in input filed use name="upload[]" it returns an array so it makes the code much cleaner ... And to upload files use loops ( I used for loop in to see demonstrate how to upload different files here ) you can write some js and before uploading add some validations as per your needs !
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$path = "./"; // Specifiy the path where uploaded files goes
// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);
// Loop through each file
for ($i = 0; $i < $total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a file path
if ($tmpFilePath != "") {
$target_path = $path;
$target_path = $target_path.basename($_FILES['upload']['name'][$i]);
// Upload files (YOUR IMAGES) into desired directory !
if (move_uploaded_file($tmpFilePath, $target_path)) {
$success = "success";
}
}
}
}
?>
<form action="index.php" method="POST" accept-charset="utf-8" enctype="multipart/form-data">
<input type="file" name="upload[]" multiple />
<button type="submit">Submit</button>
</form>

Trouble with a PHP Calendar

So I have made a calendar using a php class and it works fine except when the first day of the month lands on a Saturday (two examples being February 1, 2020 or August 1, 2020). I believe the issue is in the PHP class, but I will include the CSS, along with a couple screenshots of what is happening.
PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);
class Calendar{
private $month;
private $year;
private $days_of_week;
private $num_days;
private $date_info;
private $day_of_week;
public function __construct($month, $year, $days_of_week = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat')){
// server info would be here.
require_once(CONN_DB);
require_once(SESH);
$this->month = $month;
$this->year = $year;
$this->days_of_week = $days_of_week;
$this->num_days = cal_days_in_month(CAL_GREGORIAN, $this->month, $this->year);
$this->date_info = getdate(strtotime('first day of', mktime(0,0,0,$this->month,1,$this->year)));
$this->day_of_week = $this->date_info['wday'];
}
public function show($conn){
$output = '<div class="calRow">';
foreach($this->days_of_week as $day){
$output .= '<div class="calCol-1 header">'.$day.'</div>';
}
$output .= '</div>';
$output .= '<div class="calRow dayRow">';
if($this->day_of_week > 0){
$output .= '<div class="calCol-'.$this->day_of_week.' empty"></div>';
}
//This is where I think the issue is...
$current_day = 1;
while($current_day <= $this->num_days){
if($this->day_of_week == 7){
$this->day_of_week = 0;
$output .= '</div><div class="calRow dayRow">';
}
$day_date = str_pad($current_day,2,'0',STR_PAD_LEFT);
$mnth_w_zero = str_pad($this->month,2,'0',STR_PAD_LEFT);
$event_date = $this->year . '-' . $mnth_w_zero . '-' . $day_date;
$output .= '<div class="calCol-1 day">';
$output .= '<div class="date">'.$day_date.'</div>';
$output .= '<div class="slots" id="'.$event_date.'"></div>';
$output .= '</div>';
$current_day++;
$this->day_of_week++;
}
// bottom of issue spot...
if($this->day_of_week != 7){
$remaining_days = 7 - $this->day_of_week;
$output .= '<div class="calCol-'.$remaining_days.' empty"></div>';
}
$output .= '</div>';
echo $output;
}
}
CSS
.cal_selector {
width: 100%;
text-align: center;
margin-bottom: 5px;
}
#calendar_div {
width: 100%;
height: 95%;
border-right: 1px solid var(--mainnav-background-color);
}
.dayRow {
height: 15.8%;
}
div.header {
text-align: center;
background-color: var(--mainnav-background-color);
}
div.empty {
height: 100%;
background-color: grey;
}
div.day {
height: 100%;
padding: 0px;
}
div.date {
padding: 2px;
}
span.event {
text-align: left;
background-color: var(--main-front-color);
color: white;
font-size: 12px;
padding: 2px;
height: 20px;
border-radius: 4px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.spread {
position: absolute;
z-index: 2;
}
.eventSlot {
padding: 0;
background-color: var(--main-front-color);
margin-bottom: 1px;
border-radius: 4px;
}
.eventSlot:hover .infopane {
display: block;
}
.infopane {
display: none;
position: absolute;
z-index: 3;
background-color: var(--mainnav-background-color);
border: 1px solid var(--main-front-color);
border-radius: 4px;
padding: 10px;
}
.optionPane {
text-align: center;
}
.calOpts {
padding: 2px;
}
.calCol-1 {
width: 14.28%;
}
.calCol-2 {
width: 28.57%;
}
.calCol-3 {
width: 42.86%;
}
.calCol-4 {
width: 57.15%;
}
.calCol-5 {
width: 71.44%;
}
.calCol-6 {
width: 85.73%;
}
.calCol-7 {
width: 99.99%;
}
[class*="calCol-"] {
border-left: 1px solid var(--mainnav-background-color);
float: left;
padding: 10px;
}
.calRow {
border-bottom: 1px solid var(--mainnav-background-color);
}
.calRow::after {
content: "";
clear: both;
display: table;
}
Top PHP on myCalendar.php (calls myCalendar_class.php)
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//server info here
require_once(CONN_DB);
require_once(SESH);
require_once(CALENDAR_CLASS);
?>
HTML on myCalendar.php
<script src="Scripts/Calendar/scripts_calendar.js"></script>
<span class="pageTitle">My Calendar</span>
<div class="cal_selector">
<div class="cal_selector_center">
<select id="month_select" name="month_select" style="width:150px">
<option value='1'>January</option>
<option value='2'>February</option>
<option value='3'>March</option>
<option value='4'>April</option>
<option value='5'>May</option>
<option value='6'>June</option>
<option value='7'>July</option>
<option value='8'>August</option>
<option value='9'>September</option>
<option value='10'>October</option>
<option value='11'>November</option>
<option value='12'>December</option>
</select>
<select id='year_select' name="year_select" style="width:75px;">
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2024">2024</option>
<option value="2025">2025</option>
</select>
</div>
</div>
<div id="calendar_div"></div>
JQuery
function create_event_slots() {
$('.slots').each(function() {
var id = $(this).attr('id');
var d = new Date(id + 'T01:00:00');
var ms = d.getTime();
var div = "";
for (i = 0; i <= 20; i++) {
div += '<div class="eventSlot" id="' + ms + '_' + i + '"></div>';
}
$(this).html(div);
});
}
function change_calendar(mnth, year) {
var str = 'month=' + mnth + '&year=' + year;
$.ajax({
type: 'GET',
data: str,
url: 'Functions/load_calendar.php',
success: function(result) {
$('#calendar_div').html(result);
create_event_slots();
update_events(mnth, year);
}
});
}
function set_selects_to_current_month() {
var d = new Date();
var m = d.getMonth() + 1;
var y = d.getFullYear();
var m_sel = $('#month_select');
var y_sel = $('#year_select');
m_sel.val(m);
y_sel.val(y);
}
$(document).ready(function() {
set_selects_to_current_month();
change_calendar($('#month_select').val(), $('#year_select').val());
$('#month_select').change(function() {
change_calendar($(this).val(), $('#year_select').val());
});
$('#year_select').change(function() {
change_calendar($('#month_select').val(), $(this).val());
});
});
Correct Result
a correctly rendered calendar
Incorrect result
enter image description here
The problem was actually in the CSS.
New CSS snippet
.calCol-1 {
width: 14.27%;
}
.calCol-2 {
width: 28.56%;
}
.calCol-3 {
width: 42.85%;
}
.calCol-4 {
width: 57.14%;
}
.calCol-5 {
width: 71.43%;
}
.calCol-6 {
width: 85.72%;
}
.calCol-7 {
width: 99.98%;
}
Old CSS Snippet
.calCol-1 {
width: 14.28%;
}
.calCol-2 {
width: 28.57%;
}
.calCol-3 {
width: 42.86%;
}
.calCol-4 {
width: 57.15%;
}
.calCol-5 {
width: 71.44%;
}
.calCol-6 {
width: 85.73%;
}
.calCol-7 {
width: 99.99%;
}
Essentially, for whatever reason in this situation the container was .01 percent too big to fit in the appropriate row.

Autocomplete Textbox from Active Directory usind LDAP Users in 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!";
} }

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