can css attribute matching be caseinsensitive ? with SASS? - javascript

I'm formatting links depending on the kind of file they link to.
a[href$=".doc"] { background: url(icon-doc.png) left; padding-left: 30px; }
My problem is, attribute-matching seems to be case sensitive. Is it possible to have CSS match any case combinations?
Or is it possible to have compass/sass generating all the differing case variations? like
a[href$=".doc"], a[href$=".Doc"], a[href$=".dOc"] { ... }
Or do I need to make some js to lowercase all attributes?

It was harder than i thought but i'm too stubborn to quit :P
$ext-s : ("gif", "jpg", "jpeg", "png", "project");
#function to-upper-case-at($s, $n) {
#if $n < 1 {
#return $s;
}
#if str-length($s) == 1 {
#return to-upper-case($s);
}
$before : "";
$after : "";
$char: "";
#if $n > 1 {
$before : str-slice($s, 1, $n - 1);
}
#if $n < str-length($s) {
$after : str-slice($s, $n + 1);
}
$char: to-upper-case(str-slice($s, $n, $n));
#return $before + $char + $after;
}
#function power ($x, $n) {
$ret: 1;
#if $n >= 0 {
#for $i from 1 through $n {
$ret: $ret * $x;
}
} #else {
#for $i from $n to 0 {
$ret: $ret / $x;
}
}
#return $ret;
}
#function bin-mask-list($dec-int) {
$r : $dec-int;
$res : ();
$dig : 0;
$last : false;
#while $last == false {
$m : $r % 2;
#if $m != 0 {
$dig : 1;
}
#else {
$dig : 0;
}
$res : join($dig, $res);
#if ($r == 1) or ($r == 0) {
$last : true;
}
$r : floor($r / 2);
}
#return $res;
}
#function all-cases($string) {
$case-list: ($string);
$length : str-length($string);
#for $i from 1 to power(2, $length) {
$mask : bin-mask-list($i);
$res-string : $string;
#while $length > length($mask) {
$mask : join(0, $mask);
}
#for $j from 1 through $length {
$digit : nth($mask, $j);
#if $digit == 1{
$res-string : to-upper-case-at($res-string, $j);
}
}
$case-list : append($case-list, $res-string);
}
#return $case-list;
}
#each $ext in $ext-s {
$all-c : all-cases($ext);
#each $c in $all-c {
a[href$=".#{$c}"] { background: url(icon-doc.#{$c}) left; padding-left: 30px; }
}
}
It will output around 2k lines of css like this one:
/* line 85, ../scss/test.scss */
a[href$=".gif"] {
background: url(icon-doc.gif) left;
padding-left: 30px;
}
/* line 85, ../scss/test.scss */
a[href$=".giF"] {
background: url(icon-doc.giF) left;
padding-left: 30px;
}
/* line 85, ../scss/test.scss */
a[href$=".gIf"] {
background: url(icon-doc.gIf) left;
padding-left: 30px;
}
/* line 85, ../scss/test.scss */
a[href$=".gIF"] {
background: url(icon-doc.gIF) left;
padding-left: 30px;
}
/* line 85, ../scss/test.scss */
a[href$=".Gif"] {
background: url(icon-doc.Gif) left;
padding-left: 30px;
}
/* line 85, ../scss/test.scss */
a[href$=".GiF"] {
background: url(icon-doc.GiF) left;
padding-left: 30px;
}
/* line 85, ../scss/test.scss */
a[href$=".GIf"] {
background: url(icon-doc.GIf) left;
padding-left: 30px;
}
/* line 85, ../scss/test.scss */
a[href$=".GIF"] {
background: url(icon-doc.GIF) left;
padding-left: 30px;
}
/* line 85, ../scss/test.scss */
a[href$=".jpg"] {
background: url(icon-doc.jpg) left;
padding-left: 30px;
}

URLs are all case sensitive, so yes, you need to make your links consistent.
CSS file name case sensitivity & Css file caching

Related

How can I get jQuery code working on touch screen device

I use some jQuery code for my range slider, it works well on PC but not working on a touch device and I don't know how to fix it.
I have tried different ways such as:
_ Use on('touchmove', rangeInputChangeEventHandler); instead of on('input', rangeInputChangeEventHandler); but it still not working
_ Add $('input[type="range"]').on( 'touchstart', rangeInputChangeEventHandler); below $('input[type="range"]').on( 'input', rangeInputChangeEventHandler); line and it's still not working.
Here is my code, it includes Javascript, jQuery, HTML, and CSS to run code:
Javascript
//main function change number of slider when dragging
(function() {
// function to round up number
function lamtronTien(number) {
// set rounded, currentForamt, tienFormat as varibale
var rounded = Math.round(number / 1000000) * 1000000;
var currentFormat = new Intl.NumberFormat("vn-VN");
var tienFormat = currentFormat.format(rounded);
//
return tienFormat;
}
//function to turn number into word
function docSoTien(number) {
// replace "," with ""
number = number.replaceAll(",", "");
// set variable ty and trieu as below
var ty = Math.pow(10, 9);
var trieu = Math.pow(10, 6);
// when number = 0 return 0
if (number === "0") {
return 0;
// else number is larger than ty
} else {
if (number >= ty) {
// set variable as floor of "number" devided by "ty"
var hangTy = Math.floor(number / ty);
// if hangTy is greater than 1 then result
if (hangTy >= 1) {
// set varibales
var hangTrieu = number % ty;
var hangTrieu = Math.floor(hangTrieu / trieu);
if (hangTrieu > 0) {
return (hangTy + " Tỷ " + hangTrieu + " Triệu");
// else
} else {
return (hangTy + " Tỷ");
}
}
} else {
// var hangTrieu = number % ty;
var hangTrieu = Math.floor(number / trieu);
if (hangTrieu > 0) {
return (hangTrieu + " Triệu");
}
}
}
}
// function to apply change when there is a change in number input
function rangeInputChangeEventHandler(e) {
// set attribute name as rangeGroup
var rangeGroup = $(this).attr('name'),
minBtn = $(this).parent().children('.min'),
maxBtn = $(this).parent().children('.max'),
// get value of range_min, range_max
range_min = $(this).parent().children('.range_min'),
range_max = $(this).parent().children('.range_max'),
minVal = parseInt($(minBtn).val()),
maxVal = parseInt($(maxBtn).val()),
origin = e.originalEvent.target.className;
// if origin
if (origin === 'min' && minVal > maxVal - 5) {
$(minBtn).val(maxVal - 5);
}
var minVal = parseInt($(minBtn).val());
$(range_min).html(docSoTien(lamtronTien(minVal)));
// if origin is max and maxVal minus 5 is smaller than minVal
if (origin === 'max' && maxVal - 5 < minVal) {
$(maxBtn).val(5 + minVal);
}
var maxVal = parseInt($(maxBtn).val());
if (docSoTien(lamtronTien(maxVal)) === '3 Tỷ') {
$(range_max).html('> 3 Tỷ');
} else {
// apply to range_max
$(range_max).html(docSoTien(lamtronTien(maxVal)));
};
}
// apply change to input type range
$('input[type="range"]').on('input', rangeInputChangeEventHandler);
})();
/* adjust */
input[type='range'] {
width: 210px;
height: 30px;
padding: 20px;
overflow: hidden;
cursor: pointer;
outline: none;
}
/* adjust */
input[type='range'],
input[type='range']::-webkit-slider-runnable-track,
input[type='range']::-webkit-slider-thumb {
-webkit-appearance: none;
background: none;
}
/* adjust */
input[type='range']::-webkit-slider-runnable-track {
width: 300px;
height: 1px;
background: #003D7C;
}
/* adjust */
input[type='range']:nth-child(2)::-webkit-slider-runnable-track {
background: none;
}
/* adjust */
input[type='range']::-webkit-slider-thumb {
position: relative;
height: 15px;
width: 15px;
margin-top: -7px;
background: #fff;
border: 1px solid #003D7C;
border-radius: 25px;
z-index: 1;
}
/* adjust */
input[type='range']:nth-child(1)::-webkit-slider-thumb {
z-index: 2;
}
.rangeslider {
height: 60px;
width: 210px;
display: inline-block;
margin-top: -5px;
margin-left: 20px;
}
/* adjust rangeslider input */
.rangeslider input {
position: absolute;
}
/* adjust rangeslider */
.rangeslider {
position: absolute;
}
/* adjust rangeslider span*/
.rangeslider span {
margin-top: 30px;
left: 0;
}
/* adjust rangeslider right thumb */
.rangeslider .right {
position: relative;
float: right;
margin-right: -70px;
margin-top: -3px;
}
<!-- slider -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- slider -->
<div class="slider-group">
<div class="rangeslider">
<input class="min" name="min" type="range" min="0" max="3000000000" value="0" />
<input class="max" name="max" type="range" min="0" max="3000000000" value="3000000000" />
<span class="range_min light left">0</span>
<span class="range_max light right"> > 3 Tỷ</span>
</div>
</div>
and my site: link
Can anyone tell me what is the problem and how to fix it? Thank you!

Uploading dragged images in javascript?

So, I was making a uploading system in php, Before you can choose an image. Now you can either choose an image or just drag the image on the uploading system. The problem that I'm having, If I choose and image and then upload it, It works fine and the name of the images are shown before uploading but when I drag an image the names are shown but I can't seem to upload it. Is there anyway to fix this problem I'm having, I have no idea how to fix it.
HTML:
<div class="container">
<div class="add-form">
<h1 class="text-center"><font face="fantasy" size = "10"><center>Please Insert new image</center></font></h1>
<form method="post" enctype="multipart/form-data" id="FormID" onsubmit="uploadFiles(event)">
<label for = "name" id = "LabelName"><font face = fantasy size = "5">
<img src = "https://image.flaticon.com/icons/png/512/1233/1233986.png" width = "50">
<br>
UserName</font></label>
<input class = "UsernameUpload" id = "name" type="text" name="user_name" class="form-control">
<label for = "image" id = "fileLabel"
ondragover = "overrideDefault(event);fileHover();"
ondragenter = "overrideDefault(event);fileHover();"
ondragleave = "overrideDefault(event);fileHoverEnd();"
ondrop = "overrideDefault(event);fileHoverEnd();addFiles(event);">
<font face = "fantasy" size = "5">
<img src = "https://image.flaticon.com/icons/png/512/1180/premium/1180674.png" width = "50">
<br>
<span id = "fileLabelText">Select image to upload Or Drag N Drop</font></span>
<br>
</label>
<input multiple onchange = "addFiles(event)" id = "image" type="file" onchange ="unlock()" name="profile" class="form-control2" accept="*/image">
<button class = "uploadButton" type="submit" value = "submit" name="btn-add" onClick = "return validate()" action = "index.php"><font face = "calibri" size = "4">upload</font></button>
<div id = "error"><font face = "fantasy">Please fill up the username and select and image</font></div>
</form>
</div>
<hr style="border-bottom: 5px blue solid;">
</div>
Css code:
<style type = "text/css">
body{
background-color: lightblue;
}
#FormID {
margin: 16px;
text-align: center;
border-radius: 8px;
overflow: hidden;
transition: 0.5s;
}
#FormID #fileLabel {
background-color: rgba(0, 255, 0, 0.5);
display: block;
padding: 16px;
position: relative;
cursor: pointer;
}
#FormID #image {
display: none;
}
#FormID #fileLabel:after,
#FormID #fileLabel:before {
position: absolute;
content: "";
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: #fff;
z-index: -2;
border-radius: 8px 8px 0 0;
}
#FormID #fileLabel:before {
z-index: -1;
background: repeating-linear-gradient(
45deg,
transparent,
transparent 5%,
black 5%,
black 10%
);
opacity: 0;
transition: 0.5s;
}
#FormID.fileHover #fileLabel:before {
opacity: 0.25;
}
#FormID .uploadButton {
border: 0;
outline: 0;
width: 100%;
padding: 8px;
background-color: limeGreen;
color: #fff;
cursor: pointer;
}
#FormID.fileHover {
box-shadow: 0 0 16px limeGreen;
}
Javascript code:
<script>
function validate()
{
var username = document.getElementById("name");
var img = document.getElementById("image");
if(username.value.trim()=="") {
var myDiv = document.getElementById("error");
username.style.border = "solid 3px red";
myDiv.innerHTML = '<font face = "fantasy" size="4" color = "red">username not entered</font>';
return false;
}
else if (username.value.length<8){
var myDiv = document.getElementById("error");
username.style.border = "solid 3px red";
myDiv.innerHTML = '<font face = "fantasy" size="4" color = "red">username need to be atleast 8 characters long</font>';
return false;
}
else if (img.value.trim()=="") {
var myDiv = document.getElementById("error");
img.style.border = "solid 3px red";
myDiv.innerHTML = '<font face = "fantasy" size="4" color = "red">Please Select an image</font>';
return false;
}
}
var FormID = document.getElementById("FormID");
var fileLabelText = document.getElementById("fileLabelText");
var uploadStatus = document.getElementById("uploadStatus");
var image = document.getElementById("image");
var droppedFiles;
function overrideDefault(event) {
event.preventDefault();
event.stopPropagation();
}
function fileHover() {
FormID.classList.add("fileHover");
}
function fileHoverEnd() {
FormID.classList.remove("fileHover");
}
function addFiles(event) {
droppedFiles = event.target.files || event.dataTransfer.files;
showFiles(droppedFiles);
}
function showFiles(files) {
if (files.length > 1) {
fileLabelText.innerText = files.length + " files selected";
} else {
fileLabelText.innerText = files[0].name;
}
}
</script>
EDIT: This is PHP code also:
<?php
include("config.php");
if(isset($_GET['delete_id']))
{
$stmt_select=$db_conn->prepare('SELECT * FROM tbl_user WHERE id=:uid');
$stmt_select->execute(array(':uid'=>$_GET['delete_id']));
$imgRow=$stmt_select->fetch(PDO::FETCH_ASSOC);
unlink("uploads/".$imgRow['picprofile']);
$stmt_delete=$db_conn->prepare('DELETE FROM tbl_user WHERE id =:uid');
$stmt_delete->bindParam(':uid', $_GET['delete_id']);
if($stmt_delete->execute())
{
?>
<script>
window.location.href=('index.php');
</script>
<?php
}else
?>
<script>
window.location.href=('index.php');
</script>
<?php
}
?>
<?php
if(isset($_POST['btn-add']))
{
$name=$_POST['user_name'];
$images=$_FILES['profile']['name'];
$path = "uploads/";
$rand=rand(1000, 1000000);
$filename = "$rand.jpg";
$filepath = "$path$filename";
function correctImageOrientation($filename) {
if (function_exists('exif_read_data')) {
$exif = exif_read_data($filename);
if($exif && isset($exif['Orientation'])) {
$orientation = $exif['Orientation'];
if($orientation != 1){
$img = imagecreatefromjpeg($filename);
$deg = 0;
switch ($orientation) {
case 3:
$deg = 180;
break;
case 6:
$deg = 270;
break;
case 8:
$deg = 90;
break;
}
if ($deg) {
$img = imagerotate($img, $deg, 0);
}
// then rewrite the rotated image back to the disk as $filename
imagejpeg($img, $filename, 95);
} // if there is some rotation necessary
} // if have the exif orientation info
} // if function exists
}
$imgExt=strtolower(pathinfo($images,PATHINFO_EXTENSION));
if (move_uploaded_file($_FILES["profile"]["tmp_name"], $filepath)){
$images = imagecreatefromjpeg($filepath);
}
correctImageOrientation($filepath);
if ($imgExt == "jpeg" || $imgExt == "jpg") {
$im = imagecreatefromjpeg($filepath);
}else if($imgExt == "png"){
$im = imagecreatefrompng($filepath);
}else if($imgExt == "gif"){
$im = imagecreatefromgif($filepath);
}
$size = getimagesize($filepath);
$width = imagesx($im);
$height = imagesy($im);
$newwidth= 800;
$newheight= 800;
if(($width/$newwidth) < ($height/$newheight)){
$y = 0;
$x = $width - (($height * $newwidth) / $newheight);
}else{
$x = 0;
$y = $height - (($width * $newheight) / $newwidth);
}
$virtual_image = imagecreatetruecolor(850, 850);
imagealphablending($virtual_image, true);
imagesavealpha($virtual_image, true);
imagecopyresampled($virtual_image,$im,0,0, $x/2, $y/2, $newwidth, $newheight, $width-$x, $height-$y);
$bgcolor = imagecolorallocatealpha($virtual_image,255,255,255,127);
imagefill($virtual_image,0,0,$bgcolor);
imagecolortransparent($virtual_image, $bgcolor);
imagejpeg($virtual_image,$filepath,100);
$stmt=$db_conn->prepare('INSERT INTO tbl_user(username, picprofile) VALUES (:uname, :upic)');
$stmt->bindParam(':uname', $name);
$stmt->bindParam(':upic', $filename);
if($stmt->execute())
{
echo "Uploaded";
header("Location:index.php");
}else
{
?>
<script>
alert("Error");
window.location.href=('index.php');
</script>
<?php
}
}
?>

Add CSS style to a specific class via javascript

I got these lines of code and want to add them only to a specific div class. So if the background is dark it should be filter: invert(1); and when the background is brighter filter: invert(0);. How can I do that? Hope you can help me...I'm still at the very beginning of understanding js.
function isDark( color ) {
var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
return ( match[1] & 255 )
+ ( match[2] & 255 )
+ ( match[3] & 255 )
< 3 * 256 / 2;
}
$('div').each(function() {console.log($(this).css("background-color"))
$(this).css("filter", isDark($(this).css("background-color")) ? 'invert(1)' : 'invert(0)');
});
You can check the condition separately in an if else statement as below.
$('div').each(function() {
var color = $(this).css("background-color");
if (isDark(color)) {
$(this).css("filter", 'invert(1)');
} else {
$(this).css("filter", 'invert(0)');
}
});
OR
if you want a css class to be added, you can do it as below
$('div').each(function() {
var color = $(this).css("background-color");
if (isDark(color)) {
$(this).addClass("inverted");
} else {
$(this).addClass("not-inverted");
}
});
in which the styles can be added for the new class in your CSS as below.
.inverted {
filter: invert(1);
}
.not-inverted {
filter: invert(0);
}
See the snippet below.
function isDark(color) {
var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
return (match[1] & 255) +
(match[2] & 255) +
(match[3] & 255) <
3 * 256 / 2;
}
/*
$('div').each(function() {console.log($(this).css("background-color"))
$(this).css("filter", isDark($(this).css("background-color")) ? 'invert(1)' : 'invert(0)');
}); */
$('div').each(function() {
var color = $(this).css("background-color");
if (isDark(color)) {
$(".logo").css("filter", 'invert(1)');
} else {
$(".logo").css("filter", 'invert(0)');
}
});
body {
height: 400vh;
}
.logo {
position: fixed;
top: 40px;
right: 20px;
background-image: url(https://image.freepik.com/free-vector/bicycle-shop-logo-design-vector_53876-40626.jpg);
background-repeat: no-repeat;
background-size: 100px;
height: 100px;
width: 100px;
background-color: black;
}
.blabla {
background-color: black;
height: 50vh;
}
.blablabla {
background-color: grey;
height: 50vh;
}
.blablablabla {
background-color: red;
height: 50vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="logo"></div>
<div class="blabla">test</div>
<div class="blablabla">test</div>
<div class="blablablabla">test</div>

Textarea which counting entered symbolys

function someFunc(){
var integer = document.getElementById('email').value.toString().length;
var symbolCount = 0 + integer;
// var last2 = 100 - integer2;
if (symbolCount >= 100) {
document.querySelector('.hidden_block').style.color = 'green';
}
else if (symbolCount <= 100) {
document.querySelector('.hidden_block').style.color = 'black';
document.querySelector('.error').style.display = "block";
}
else {
document.getElementById('max').style.color = 'black';
}
document.getElementById('symbol_count').innerHTML = symbolCount;
}
email.addEventListener("click", function(){
document.querySelector('.hidden_block').style.display = 'block';
document.getElementById('max').style.display = 'none';
});
#max, #max2 {
text-align: right;
margin-right: 55px;
}
.hidden_block {
display: none;
text-align: right;
margin-right: 55px;
}
.error {
display: none;
color: red;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<label for="email">Positive</label>
<textarea type="email" class="form-control" id="email" oninput="someFunc()" placeholder="Tell people about your experience: describe the place or activity, recommendations for travelers?"></textarea>
<p id="max">Minimal length - symbols</p>
<div class="hidden_block">
<span id="count">Symbols : <span id="symbol_count">0 </span> (minimum:100)</span>
</div>
<span class="error">Your review must be at least 100 characters long. Adding details really helps travelers.</span>
Hi everyone.I have a that simple textarea field.I need to realize something like that.When u write less than 100 words and click the outside of the email id the border color must be red.And error class must displayed.And i need to if the textarea field is empty the tag p with id max must be display block if the user will write any symbol the id max must bu display none.Thanks for help
function someFunc(){
var integer = document.getElementById('email').value.toString().length;
var symbolCount = 0 + integer;
var integerValue = document.getElementById('email');
var hidden_block = document.querySelector('.hidden_block');
var max = document.getElementById('max');
var error = document.querySelector('.error');
var positive = document.getElementById("positive");
// var last2 = 100 - integer2;
if (integer >= 1) {
hidden_block.style.display = 'inline-block';
max.style.display = 'none';
integerValue.classList.add("form-control");
} else {
hidden_block.style.display = 'none';
max.style.display = 'block';
error.style.display = "none";
positive.style.color = "#002C38";
integerValue.classList.remove("form-redBorder");
}
integerValue.addEventListener("click", function(){
error.style.display = "none";
positive.style.color = "#002C38";
integerValue.classList.remove("form-redBorder");
});
//Red error and border
document.body.addEventListener("click", function(e) {
var target = e.target || e.srcElement;
if (target !== integerValue && !isChildOf(target, integerValue)) {
error.style.display = "inline-block";
integerValue.classList.add("form-redBorder");
positive.style.color = "red";
} if (integer >= 100) {
error.style.display = "none";
integerValue.classList.remove("form-redBorder");
positive.style.color = "#002C38";
}
}, false);
function isChildOf(child, parent) {
if (child.parentNode === parent) {
return true;
} else if (child.parentNode === null) {
return false;
} else {
return isChildOf(child.parentNode, parent);
}
}
//Finished Red error and border
//Start to count symbols
if (symbolCount >= 100) {
hidden_block.style.color = 'green';
}
else if (symbolCount <= 100) {
hidden_block.style.color = 'black';
}
else {
max.style.color = 'black';
// document.getElementById('max2').style.color = 'black';
}
document.getElementById('symbol_count').innerHTML = symbolCount;
}
#email {
display: block;
padding: 6px 12px;
margin: 0 auto;
width: 90% !important;
height: 120px !important;
/*border:1px solid #44A1B7 !important;*/
}
.form-control {
margin: 0 auto;
width: 90% !important;
height: 120px !important;
border:1px solid #44A1B7;
}
#positive, #negative {
padding: 14px 15px 1px 55px;
color: #002C38;
font-size: 18px;
}
.form-redBorder {
margin: 0 auto;
border:1px solid #FF0000 !important;
}
#max, #max2 {
position: absolute;
right: 1%;
margin-right: 55px;
}
.hidden_block {
position: absolute;
right: 1%;
display: none;
text-align: right;
margin-right: 55px;
}
.error {
margin-left: 55px;
display: none;
color: #FF0000;
}
<form role="form">
<div class="form-group">
<p class="help-block">About youre site.</p>
<label for="email" id="positive">Positive</label>
<textarea type="email" id="email" oninput="someFunc()" placeholder="Your review must be at least 100 characters long<br> Adding details really helps travelers"></textarea>
<p id="max">(100 character minimum)</p><div class="hidden_block">
<span id="count">Symbols : <span id="symbol_count">0 </span> (min:100)</span>
</div>
<span class="error">Your review must be at least 100 characters long.<br> Adding details really helps travelers..</span>
</div>
</form>

Pagination does not work fine

I want to add pagination to my page using ajax. I have referred this link http://www.infotuts.com/ajax-pagination-mysql-php-and-jquery/ and tried to follow the code.
But result I got is different than the demo. http://www.infotuts.com/demo/ajax-pagination-php-mysql-jQuery/
when the page is first loaded it shows first page but numbers are starting from 17 and when I move from page to page in between shows blank records for some page.
Not working like demo: http://www.infotuts.com/demo/ajax-pagination-php-mysql-jQuery/
Also dose not show which page is selected.
Here is link to my page :
http://104.131.162.126/agtvapp/index.php
dbmanipulate.php
<?php
include('Database.php');
$limit = 3;
$adjacent = 3;
if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];
call_user_func($actionfunction,$_REQUEST,$limit,$adjacent);
}
function showData($data,$limit,$adjacent){
$page = $data['page'];
if($page==1){
$start = 0;
}
else{
$start = ($page-1)*$limit;
}
$database = new Database(Constants::DBHOST,Constants::DBUSER,Constants::DBPASS,Constants::DBNAME);
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("select * from posts order by pt_id asc");
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt->execute();
$rows = $stmt->fetchall(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
$stmt = $dbConnection->prepare("select * from posts order by pt_id asc limit $start,$limit");
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt->execute();
$data = $stmt->fetchall(PDO::FETCH_ASSOC);
$str ='<table><tr><th>Title</th><th>Description</th><th>Likes</th><th>Views</th><th>Url</th></tr>';
if(count($data)>0){
foreach($data as $row){
$str .= '<tr><td>' . $row['title'] . '</td> <td>' . $row['description'] . '</td><td>'.$row['likes'].'</td><td>'.$row['views'].'</td>';
if (strcmp($row['url_type'],"2") == 0 || strcmp($row['url_type'],"3") == 0)
{
$str .= '<td><image alt="Image not found" onerror="this.onerror=null;this.src=\'na.jpg\';" src="'.$row['thumb_url'].'" height="150" width="150"></image></td></tr>';
/* $posts.= '<td>'.$row['url'].'</td></tr>';*/
}
elseif(strcmp($row['url_type'],"6") == 0){
// $parts = parse_url($row['url']);
// $urls=$parts['scheme'] . '://' . $parts['host'] . $parts['path'];
$thumb_url = $row['url'];
$url = $thumb_url . "media";
/* $posts.= '<td>'.$thumb_url.'</td></tr>';*/
$str .= '<td><image alt="Image not found" onerror="this.onerror=null;this.src=\'na.jpg\';" src="'.$row['thumb_url'].'" height="150" width="150"></image></td></tr>';
}
elseif(strcmp($row['url_type'],"7") == 0)
{
$str = substr($row['url'], 0, strrpos($row['url'], '?'));
$thumb_url = $str.'media';
/* $posts.= '<td>'.$thumb_url.'</td></tr>';*/
$str .= '<td><image alt="Image not found" onerror="this.onerror=null;this.src=\'na.jpg\';" src="'.$thumb_url.'" height="150" width="150"></image></td></tr>';
}
elseif(strpos($row['url'],"https://scontent.fbom") !==false )
{
$str .= '<td><image alt="Image not found" onerror="this.onerror=null;this.src=\'na.jpg\';" src="'.$row['url'].'" height="150" width="150"></image></td></tr>';
}
elseif(strpos($row['url'],"https://www.facebook.com/") !==false){
$facebookVideoId=getFacebookVideoID($row['url']);
//create thumbnail link and videos link
$json = file_get_contents('https://graph.facebook.com/'.$facebookVideoId.'');
$obj = json_decode($json);
//add thumbnail and video link in array
$thumb_url = $obj->picture;
$url =$obj->source;
$str .= '<td><image alt="Image not found" onerror="this.onerror=null;this.src=\'na.jpg\';" src="'.$thumb_url.'" height="150" width="150"></image></td></tr>';
}
elseif(strcmp($row['url_type'],"1") == 0)
{
$myvideo = $row['url'];
$url = "videos/".$myvideo;
$str .= '<td><image alt="Image not found" onerror="this.onerror=null;this.src=\'na.jpg\';" src="'.$url.'" height="150" width="150"></image></td></tr>';
}
elseif(strcmp($row['url_type'],"0") == 0)
{
$myImage = $row['url'];
$url = "images/".$myImage;
/* $posts.= '<td>'.$url.'</td></tr>';*/
$str .= '<td><image alt="Image not found" onerror="this.onerror=null;this.src=\'na.jpg\';" src="'.$url.'" height="150" width="150"></image></td></tr>';
}
else{
$str .= '<td>'.$row['url'].'</td></tr>';
}
}
} else {
$str.='<td>No data found</td>';
}
function getFacebookVideoID($url) {
preg_match("~/videos/(?:t\.\d+/)?(\d+)~i", $url, $matches);
return $matches[1];
}
$str.='</table>';
echo $str;
pagination($limit,$adjacent,$count,$page);
}
function pagination($limit,$adjacents,$count,$page){
$pagination='';
if ($page == 0) $page = 1; //if no page var is given, default to 1.
$prev = $page - 1; //previous page is page - 1
$next = $page + 1; //next page is page + 1
$prev_='';
$first='';
$page = $count/$limit;
$lastpage = ceil($page);
$next_='';
$last='';
if($lastpage > 1)
{
//previous button
if ($page > 1)
$prev_.= "<a class='page-numbers' href=\"?page=$prev\">previous</a>";
else{
//$pagination.= "<span class=\"disabled\">previous</span>";
}
//pages
if ($lastpage < 5 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
$first='';
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a class='page-numbers' href=\"?page=$counter\">$counter</a>";
}
$last='';
}
elseif($lastpage > 3 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
$first='';
if($page < 1 + ($adjacents * 2))
{
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a class='page-numbers' href=\"?page=$counter\">$counter</a>";
}
$last.= "<a class='page-numbers' href=\"?page=$lastpage\">Last</a>";
}
//in middle; hide some front and some back
elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
{
$first.= "<a class='page-numbers' href=\"?page=1\">First</a>";
for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a class='page-numbers' href=\"?page=$counter\">$counter</a>";
}
$last.= "<a class='page-numbers' href=\"?page=$lastpage\">Last</a>";
}
//close to end; only hide early pages
else
{
$first.= "<a class='page-numbers' href=\"?page=1\">First</a>";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a class='page-numbers' href=\"?page=$counter\">$counter</a>";
}
$last='';
}
}
if ($page < $counter - 1)
$next_.= "<a class='page-numbers' href=\"?page=$next\">next</a>";
else{
//$pagination.= "<span class=\"disabled\">next</span>";
}
$pagination = "<div class=\"pagination\">".$first.$prev_.$pagination.$next_.$last;
//next button
$pagination.= "</div>\n";
}
echo $pagination;
}
?>
script
$(function(){
$.ajax({
url:"dbmanupulate.php",
type:"POST",
data:"actionfunction=showData&page=1",
cache: false,
success: function(response){
$('#pagination').html(response);
}
});
$('#pagination').on('click','.page-numbers',function(){
$page = $(this).attr('href');
$pageind = $page.indexOf('page=');
$page = $page.substring(($pageind+5));
$.ajax({
url:"dbmanupulate.php",
type:"POST",
data:"actionfunction=showData&page="+$page,
cache: false,
success: function(response){
$('#pagination').html(response);
}
});
return false;
});
});
style
#mhead{
background-color: #f5f5f5;
border: 1px solid #e3e3e3;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
text-align: center;
font-family: georgia;
}
#pagination table{
width:960px;
margin:0px auto;
font-family:Tahoma,Arial,Verdana,sans-serif;
font-size:13px;
padding:4px;
border-collapse: collapse;
}
.head{
background:lightseagreen;
}
#pagination table tr td{
padding: 8px;
text-transform:capitalize;
border:1px solid #d1d1d1;
}
.pagination{
width:600px;
margin:0px auto;
}
.pagination .current{
padding: 4px 10px;
color: black;
margin: 1px 0px 9px 6px;
display: block;
text-decoration:none;
float: left;
text-transform: capitalize;
background: whitesmoke;
}
.pagination .page-numbers{
padding: 4px 10px;
color: white !important;
margin: 1px 0px 9px 6px;
display: block;
text-decoration:none;
float: left;
text-transform: capitalize;
background: #00b4cc;
}
I am not getting the issue,please help, thank you..
You have used the same variable $page inside your pagination().So original $page is overwrite by new value.
Change your code:
$mpage = $count/$limit; //in your code it is => *$page = $count/$limit;*
$lastpage = ceil($mpage); //in your code it is => *$lastpage = ceil($page)*

Categories

Resources