Onclick javascript function doesn't work on first click - javascript

I've wrote a code to hide/show a div by clicking on a "p" element, but at first click nothing happens.
Only from 2nd click the code works as expected.
I've read some similar questions and I've understood that it's probably a style problem.
So I've tried to change style (without really knowing what I was doing) but I wasn't lucky.
I've also another problem: the "p" element sometimes covers an input and I've not understood how to have it on the bottom right of the div but below every other element.
<!DOCTYPE html>
<html>
<head>
<style>
.Class1 {
position:relative;
display: inline-block;
width: 48%;
margin: 3px;
border: 3px solid #CCC;
}
.Class2 {
position:absolute;
bottom:0;
right:0;
border: 1px solid #CCC;
margin:1px;
background: #FFC;
}
.Fields {
clear: both;
border: 1px solid #CCC;
display: inline-block;
margin:3px;
}
.H_p {
border: 1px solid #CCC;
display: inline-block;
}
.Opt {
border: 1px solid #CCC;
display: none;
}
</style>
</head>
<body>
<h2>My test</h2>
<?php
$Divs = array('Div1'=>'Class1',
'Div2'=>'Class1',
'Div3'=>'Class1',
'Div4'=>'Class1',
'Div5'=>'Class1');
$AskToShow=array("Field1"=>"1.1.1", "Field2"=>"1.2.1", "Field3"=>"1.3.1");
foreach ($Divs as $Name=>$Class){
echo '
<div class="'.$Class.'">';
echo $Name.'<br/>';
foreach ($AskToShow as $I_Name=>$Id){
echo '
<label>'.$I_Name.'</label>
<input type="text" id="'.$Id.'" class="Fields"/>';
}
echo '
<p id="Btn_Opt'.$Name.'" class="Class2" >Mostra campi opzionali</p>';
echo '
<div id=Opt'.$Name.' name="Opt'.$Name.'" class="Opt" >';
foreach ($AskToShow as $H_Name=>$Id){
echo'
<p id="H_'.$Id.'" class="H_p">'.$H_Name.'</p>';
}
echo '
</div>';
echo '
</div>';
}
?>
<script>
var MyClass = document.getElementsByClassName("Class2");
var myFunction = function() {
var SenderId = this.id;
var SubId = SenderId.substring(SenderId.indexOf('_')+1)
var SubSH = document.getElementById(SubId);
if (SubSH.style.display == 'none'){
SubSH.style.display = 'inline-block';
}else{
SubSH.style.display = 'none';
}
};
for (var i = 0; i < MyClass.length; i++) {
MyClass[i].addEventListener('click', myFunction, false);
}
</script>
</body>
</html>

The thing is that when you do SubSH.style.display you are checking only inline style so something which is inn <your-tag style='...'/> but you have it in your stylesheet so it is not accessible by this method. try to change your function a bit - for example
var myFunction = function() {
var SenderId = this.id;
var SubId = SenderId.substring(SenderId.indexOf('_')+1)
var SubSH = document.getElementById(SubId);
var style = window.getComputedStyle(SubSH);
if (style.display == 'none'){
SubSH.style.display = 'inline-block';
}else{
SubSH.style.display = 'none';
}
};
by using window.getComputedStyle(SubSH); you are checking style which is aware of all your classes and csses

Please find the working code below
<!DOCTYPE html>
<html>
<head>
<style>
.Class1 {
position:relative;
display: inline-block;
width: 48%;
margin: 3px;
border: 3px solid #CCC;
}
.Class2 {
position:relative;
bottom:0;
right:0;
border: 1px solid #CCC;
margin:1px;
background: #FFC;
display: inline-block;
float:right;
}
.Fields {
clear: both;
border: 1px solid #CCC;
display: inline-block;
margin:3px;
}
.H_p {
border: 1px solid #CCC;
display: inline-block;
}
.Opt {
border: 1px solid #CCC;
display: none;
}
</style>
</head>
<body>
<h2>My test</h2>
<?php
$Divs = array(
'Div1' => 'Class1',
'Div2' => 'Class1',
'Div3' => 'Class1',
'Div4' => 'Class1',
'Div5' => 'Class1'
);
$AskToShow = array(
"Field1" => "1.1.1",
"Field2" => "1.2.1",
"Field3" => "1.3.1"
);
foreach ($Divs as $Name => $Class) {
echo '
<div class="' . $Class . '">';
echo $Name . '<br/>';
foreach ($AskToShow as $I_Name => $Id) {
echo '
<label>' . $I_Name . '</label>
<input type="text" id="' . $Id . '" class="Fields"/>';
}
echo '
<div id=Opt' . $Name . ' name="Opt' . $Name . '" class="Opt" >';
foreach ($AskToShow as $H_Name => $Id) {
echo '
<p id="H_' . $Id . '" class="H_p">' . $H_Name . '</p>';
}
echo '
</div>';
echo '
<div style="clear:both;"></div>';
echo '
<p id="Btn_Opt' . $Name . '" class="Class2" >Mostra campi opzionali</p>';
echo '
</div>';
}
?>
<script>
var MyClass = document.getElementsByClassName("Class2");
var myFunction = function() {
var SenderId = this.id;
var SubId = SenderId.substring(SenderId.indexOf('_')+1)
var SubSH = document.getElementById(SubId);
if (window.getComputedStyle(SubSH, null).display == 'none'){
SubSH.style.display = 'inline-block';
} else {
SubSH.style.display = 'none';
}
};
for (var i = 0; i < MyClass.length; i++) {
MyClass[i].addEventListener('click', myFunction, false);
}
</script>
</body>
</html>

Related

Dynamic nested tabs using php and mysql

I am a biginner to php and mysql coding. I am trying to create nested tabs dynamically.
I have created nested tabs using html, css, js. I mentioned the code below for the same. My question is how to achieve the same result dynamically using php and mysql.
Can anyone please tell me the php code for nested tabs.
Thanks in advance!!
$(".stock li:first").addClass("current");
$(".tab-inhalt:first").fadeIn();
$(".tab-content:first").fadeIn();
$(".plaene a").click(function(event) {
event.preventDefault();
$(this).parent().addClass("current");
$(this).parent().siblings().removeClass("current");
var tab = $(this).attr("href");
$(".tab-content").not(tab).css("display", "none");
$(tab).fadeIn();
$("li:first a",tab).click();
});
$(".reiter a").click(function(event) {
event.preventDefault();
$(this).parent().addClass("current");
$(this).parent().siblings().removeClass("current");
var tab = $(this).attr("href");
$(".tab-inhalt").not(tab).css("display", "none");
$(tab).fadeIn();
});
.tab-content,
.tab-inhalt {
display: none;
}
.stock li {
text-decoration: none;
list-style: none;
display: inline-block;
margin: 0 20px 0 0;
}
.stock a {
color: #0094cd;
text-decoration: none;
list-style: none;
}
.stock li.current a {
color: #4c565c;
}
.plaene a.current {
color: #4c565c;
}
.tab-alles {
width: 100%;
background-color: #f1f2f4;
margin-top: 15px;
}
.tab-oben li {
text-decoration: none;
list-style: none;
display: inline-block;
margin: 0;
background-color: #f1f2f4;
}
.tab-oben a {
color: #0094cd;
text-decoration: none;
list-style: none;
padding: 14px 20px;
display: block;
}
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<div class="stock">
<ul class="plaene">
<li class="current">Tab1</li>
<li class="">Tab2</li>
<li class="">Tab3</li>
</ul>
</div> <!-- End: .stock -->
<div class="tab-alles">
<div class="tab-oben">
<div id="objecttabs1" class="tab-content">
<ul class="reiter">
<li class="current">InnerTab1</li>
<li>InnerTab2</li>
</ul>
</div>
<div id="objecttabs2" class="tab-content">
<ul class="reiter">
<li class="">InnerTab1</li>
<li>InnerTab2</li>
</ul>
</div>
<div id="objecttabs3" class="tab-content">
<ul class="reiter">
<li>InnerTab1</li>
<li>InnerTab2</li>
</ul>
</div>
</div> <!-- End: .tab-oben -->
<div class="tab-inhalt-all">
<div id="innertab1" class="tab-inhalt">
<div class="content">Content1</div>
</div>
<div id="innertab2" class="tab-inhalt">
<div class="content">Content2</div>
</div>
<div id="innertab3" class="tab-inhalt">
<div class="content">Content3</div>
</div>
<div id="innertab4" class="tab-inhalt">
<div class="content">Content4</div>
</div>
<div id="innertab5" class="tab-inhalt">
<div class="content">Content5</div>
</div>
<div id="innertab6" class="tab-inhalt">
<div class="content">Content6</div>
</div>
</div> <!-- End: .tab-inhalt-all -->
Unfortunately, I do not have enough reputation to leave a comment. So the only way to help you out is like this.
If you want to "generate" these tabs automatically using PHP (and MySQL?) you could do the following: (if you need help on the MySQL part as well, drop a comment and I'll edit this)
here's a we-transfer link you can download an example database from for your tabs:
https://wetransfer.com/downloads/09eedb2dd16806841befe2b7701f3fab20210325114020/d426c8
The PHP, HTML, and JS:
<?php
$servername = "";//location of the database
$username = "";//username to access
$password= "";//password to access
$dbname = "Tabs";//database you want to access
//establish connection:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//get the data from the db
$output = sqlStringGetAsArray($conn, "SELECT * FROM Tabs");//This is the "Tabs" table in the "Tabs" database
function sqlStringGetAsArray($conn, $sql=""){
$result = $conn->query($sql);
if ($conn->error){
return false;
}
$array = [];
$headers=$result->fetch_fields();
$top = [];
foreach ($headers as $header){
$name = $header->name;
array_push($top, $name);
}
array_push($array,$top);
while ($row = $result->fetch_row()){
array_push($array, $row);
}
return $array;
}
//set the output to the format we need to display:
$tabContents = [];
$first = true;
foreach($output as $val){
if($first){
$first = false;
}else{
if(!isset($tabContents[$val[1]])){
$tabContents[$val[1]] = [];
}
array_push($tabContents[$val[1]], [$val[2], $val[3]]);
}
}
?>
<html>
<head>
<link rel='stylesheet' href='./tabs.css'>
</head>
<body>
<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<div id='container'>
<div class='Tabs'>
<?php
$i1 = 0;
foreach($tabContents as $key=>$value){
if($i1==0){
echo"<div id='Tab".$i1."' class='level1 active' onclick='updateTabs(this)'>".$key."</div>";
}else{
echo"<div id='Tab".$i1."' class='level1' onclick='updateTabs(this)'>".$key."</div>";
}
$i1++;
}
?>
</div>
<div class='innerTabs'>
<?php
$i1 = 0;
foreach($tabContents as $key=>$value){
$i2 = 0;
if($i1 == 0){
echo("<div id='Tab".$i1."' class='parent visible'>");
foreach($value as $i){
if($i2 == 0){
echo"<div id='innerTab".$i2."' class='level2 active' onclick='updateInnerTabs(this)'>".$i[0]."</div>";
}else{
echo"<div id='innerTab".$i2."' class='level2' onclick='updateInnerTabs(this)'>".$i[0]."</div>";
}
$i2++;
}
$i1++;
}else{
echo("<div id='Tab".$i1."' class='parent'>");
foreach($value as $i){
if($i2 == 0){
echo"<div id='innerTab".$i2."' class='level2 active' onclick='updateInnerTabs(this)'>".$i[0]."</div>";
}else{
echo"<div id='innerTab".$i2."' class='level2' onclick='updateInnerTabs(this)'>".$i[0]."</div>";
}
$i2++;
}
$i1++;
}
echo("</div>");
}
?>
</div>
<div class='contents'>
<?php
$i1 = 0;
foreach($tabContents as $key=>$value){
$i2 = 0;
foreach($value as $i){
if($i1 == 0 && $i2 == 0){
echo"<div id='Tab".$i1."_innerTab".$i2."_content' class='level3 visible'>".$i[1]."</div>";
}else{
echo"<div id='Tab".$i1."_innerTab".$i2."_content' class='level3'>".$i[1]."</div>";
}
$i2++;
}
$i1++;
}
?>
</div>
</div>
<script>
function updateTabs(el) {
visibility(el, '.innerTabs');
$('.innerTabs').children('#' + $(el).attr('id')).addClass('visible');
updateInnerTabs($('.innerTabs').children('#' + $(el).attr('id')).children().first());
}
function updateInnerTabs(el) {
visibility(el, '.contents');
var tab = $(el).parent().attr('id') + '_';;
var innerTab = $(el).attr('id') + '_content';
$('#' + tab + innerTab).addClass('visible');
}
function visibility(el, aClass) {
$(el).siblings('.active').removeClass('active');
$(el).addClass('active');
$(aClass).children('.visible').removeClass('visible');
}
</script>
(This bit is at the bottom of the file:)
<pre>
<?php
print_r($tabContents);
?>
</pre>
</body>
</html>
the CSS:
.Tabs{
background-color: #222;
}
.level1{
padding: 16px;
color: #eee;
background-color: #222;
display: inline-block;
}
.level1.active{
color: #fff;
background-color: #4caf50;
display: inline-block;
}
.level1:hover{
color: #000;
background-color: #eee;
}
.innerTabs{
background-color: #444;
color: #eee;
}
.parent:not(.visible){
display: none;
}
.level2{
padding: 16px;
background-color: #444;
color: #fff;
display: inline-block;
}
.level2.active{
color: #fff;
background-color: #65bd68;
display: inline-block;
}
.level2:hover{
color: #000;
background-color: #eee;
display: inline-block;
}
.contents{
background-color: #ddd;
color: #000;
padding: 16px;
}
.contents div:not(.visible){
display: none;
}
Although this code is not very elegant, it gets the job done, and you can easily get Data from your Database and put it into $tabContents.
One way you could organize your table would be like so:
Bear in mind that the "Tab" value has to be the same for some if you want multiple "innerTabs" for a "tab". This example will have 1 "Tab" with 2 "innerTabs"

Live search - Ajax, PHP

I have a little problem with the live search form. Below is what I want:
This is what I want. What I have is:
And Screenshot of my problem.
The general problem of Screenshot 3 when I type something in Keyword? field, when I get the result that the field gets bigger and that is what I don't need. The result field is good, exactly what I need. So problem is, I don't need to get a bigger field Keyword? after some user enters some text into that field. Keyword? field the same size, result div size wider.
Bellow, I will paste my code.
HTML:
<div class="header-search-input-item">
<input type="text" name="search" id="search" autocomplete="off" placeholder="Keywords?" value=""/>
<div class="resultDiv"></div>
<div class="clearfix"></div>
</div>
CSS:
.clearfix { clear:both; }
.sp { clear:both; display:block; margin-bottom:30px; }
.sp a { font-weight:bold; color:#0099FF; }
label { margin-top:20px; margin-bottom:3px; font-weight:bold;}
.searchDiv {
width:130px;
}
.resultDiv {
display:none;
width:auto;
margin-top:40px;
max-height:200px;
overflow:auto;
border:1px solid #0099FF;
padding:5px;
z-index:999;
background-color:#fff;
}
.search {
width: 100%;
float: left;
margin:0;
padding:0;
}
.search .pret {
list-style:none;
clear:both;
width:100%;
height: 60px;
padding:5px 0;
border-bottom: 1px solid #fff;
}
.search .pret:hover, .search .pret:hover > a {
background-color:#0099FF;
color:#fff;
cursor:pointer;
}
.search img {
float:left;
margin:0 5px;
padding:3px;
border:1px solid #ccc;
border-radius:5px;
}
.search a {
text-decoration:none;
color:#666;
display:inline;
}
JS:
$(document).ready(function() {
$("#search").keyup(function() {
var keywords = $(this).val();
if(keywords != "") {
$.ajax({
url: "get_search_result.php",
data: {keywords : keywords},
type: "POST",
success: function(resp) {
if(resp != "") {
$(".resultDiv").html(resp).show();
} else {
$(".resultDiv").html("").hide();
}
}
});
} else {
$(".resultDiv").html("").hide();
}
});
$(document).click(function() {
$("#search").val("");
$(".resultDiv").html("").hide();
});
});
And PHP File:
<?php include("db.php");?>
<?php
if(isset($_POST['keywords'])) {
$keywords_arr = explode(",", mysqli_real_escape_string($con, $_POST['keywords']));
$like = "";
foreach($keywords_arr as $key) {
$key = trim($key);
if($key != "") $like .= " `VehiclesTitle` like '%".$key."%' or";
}
$like = substr($like, 0, -3);
$sql = "select distinct * from `tblvehicles` where ".$like." limit 20";
$res = mysqli_query($con, $sql);
echo "<ul class='search'>";
if(mysqli_num_rows($res) > 0) {
while($row = mysqli_fetch_object($res)) {
if(file_exists("admin/img/vehicleimages/".$row->Vimage1."")) $img = "admin/img/vehicleimages/".$row->Vimage1."";
else $img = "images/post_images/default.jpg";
echo "<li class='pret'><a href=''><img src='".$img."' width='50' height='50' />".$row->VehiclesTitle."</a></li>";
}
} else {
echo "<li class='pret'>No match found!</li>";
}
echo "</ul>";
echo "<div class='clearfix'></div>";
}
?>

Getting double quotes in Html element name

I'm trying to change visibility of some divs by click.
I'm adding "main" divs and "sub" divs using a php foreach loop on an array.
After that I add events using javascript to the elements having a specific class.
The problem is that the javascript function gets the name of the element with double quotes at the start and in the end.
I could solve by using a "substring" but I'm pretty new to web programming and I need to understand why this happens or I'll never improve my skills.
Below there is all my code.
<!DOCTYPE html>
<html>
<head>
<style>
.Class1 {
position:relative;
display: inline-block;
width: 48%;
margin: 3px;
border: 3px solid #CCC;
}
.Class2 {
position:absolute;
bottom:0;
right:0;
border: 1px solid #CCC;
margin:1px;
background: #FFC;
}
.H_p {
border: 1px solid #CCC;
display: inline-block;
}
.Opt {
border: 1px solid #CCC;
display: none;
}
</style>
</head>
<body>
<?php
$Divs = array('Div1'=>'Class1',
'Div2'=>'Class1',
'Div3'=>'Class1',
'Div4'=>'Class1',
'Div5'=>'Class1');
$AskToShow=array("Field1"=>"1.1.1", "Field2"=>"1.2.1", "Field3"=>"1.3.1");
foreach ($Divs as $Name=>$Class){
echo '
<div class="'.$Class.'">';
echo $Name.'<br/>';
echo '
<p id=”Btn_Opt'.$Name.'” class="Class2" >Show optionals</p>';
echo '
<div id=Opt'.$Name.' name="Opt'.$Name.'" class="Opt" >';
foreach ($AskToShow as $H_Name=>$Id){
echo'
<p id="H_'.$Id.'" class="H_p">'.$H_Name.'</p>';
}
echo '
</div>';
echo '
</div>';
}
?>
<script>
var MyClass = document.getElementsByClassName("Class2");
var myFunction = function() {
var SenderId = this.id;
alert (SenderId);
var SubId = SenderId.substring(SenderId.indexOf('_')+1)
alert (SubId);
var SubSH = document.getElementById(SubId);
if (!SubSH){
alert("Empty"); //This is the alert shown!!
}else{
alert(SubSH.name);
}
if (SubSH.style.display == 'none'){
document.getElementById(SubId).style.display = 'block';
}else{
document.getElementById(SubId).style.display = 'none';
}
};
for (var i = 0; i < MyClass.length; i++) {
MyClass[i].addEventListener('click', myFunction, false);
}
</script>
</body>
</html>
<p id=”Btn_Opt'.$Name.'” class="Class2" >Show optionals</p>';
You are using ” (RIGHT DOUBLE QUOTATION MARK) to delimit your attribute values. Only " (QUOTATION MARK) and ' (APOSTROPHE) are allowed.
The RIGHT DOUBLE QUOTATION MARK is, therefore, being treated as data and not as a delimiter.
This code example shows the three characters at a large font size so you can clearly see the difference between them.
body { font-size: 50px; }
”<br>"<br>'
This is often caused by writing HTML using a word processor instead of a text editor.
<p id=”Btn_Opt'.$Name.'” class="Class2" >Show optionals</p>';
There you used the wrong quote type ”.
Hope this fixes it.

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)*

Create UL Columns To List Files from Selected and Uploaded Files

So I am Uploading Multiple Images To Folder using Php/Html. When user selects multiple Files, They are listed in a single column, the same goes for uploading after Uploading images, i echo out the Filename with being completed or not, and they to are listed in a single column. What i am asking for help with is- How can i create (lets say 3 or more column-example) that list a max 5 or more in each column. So if the user selects 15 images then both the fileslisted and Uploaded will have 3 columns and there will be 5 listed in each. Here Is an example as well as Script. I have included a ideal situation as well. I would also like if the completed uploads be columned like the selected. Please and thanks
Demo Here
Script
<?php
$total = count($_FILES['filesToUpload']['name']);
$succes = [];
$error = [];
for($i=0; $i<$total; $i++) {
$tmpFilePath = $_FILES['filesToUpload']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "./upimages/" . $_FILES['filesToUpload']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$succes[$_FILES['filesToUpload']['name'][$i]] = true;
}else{
$errors[$_FILES['filesToUpload']['name'][$i]] = true;
}
}
}
foreach(array_keys($succes) as $suc){
$myString = $suc." was succesfull,";
$myArray = explode(',', $myString);
foreach($myArray as $my_Array){
echo $my_Array.'<br>';
}
}
foreach(array_keys($errors) as $error){
echo $error." failed to upload";
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="file-input-wrapper">
<button class="btn-file-input">Upload Documents</button>
<input type="file" accept="image/png, image/jpeg" name="filesToUpload[]" id="filesToUpload" multiple="" onChange="makeFileList();" />
<input type="hidden" name="MAX_FILE_SIZE" value="60000000" />
</div>
<p>
<strong>Files You Selected:</strong>
<ul id="fileList"><li>No Files Selected</li></ul>
<div class="file-input-wrapper1">
<button class="btn-file-input1">Upload Documents</button>
<input type="submit" value="Upload!" />
</div>
</p>
<style type="text/css">
.file-input-wrapper {
width: 400px;
height: 125px;
overflow: hidden;
position: relative;
}
.file-input-wrapper > input[type="file"] {
font-size: 200px;
position: absolute;
top: 0;
right: 0;
opacity: 0;
}
.file-input-wrapper > .btn-file-input {
display: inline-block;
width: 400px;
height: 125px;
}
.file-input-wrapper:hover > .btn-file-input {
background-color: #aaa;
}
.file-input-wrapper1 {
width: 400px;
height: 125px;
overflow: hidden;
position: relative;
}
.file-input-wrapper1 > input[type="submit"] {
font-size: 200px;
position: absolute;
top: 0;
right: 0;
opacity: 0;
}
.file-input-wrapper1 > .btn-file-input1 {
display: inline-block;
width: 400px;
height: 125px;
}
.file-input-wrapper1:hover > .btn-file-input1 {
background-color: #ffff00;
}
button {
font-size: 26px;
}
</style>
<script type="text/javascript">
function makeFileList() {
var input = document.getElementById("filesToUpload");
var ul = document.getElementById("fileList");
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
for (var i = 0; i < input.files.length; i++) {
var li = document.createElement("li");
li.innerHTML = input.files[i].name;
ul.appendChild(li);
}
if(!ul.hasChildNodes()) {
var li = document.createElement("li");
li.innerHTML = 'No Files Selected';
ul.appendChild(li);
}
}
</script>
You need three things : a table (<table>), calculate how many columns based on the files selected, and a counter for the columns that are being displayed. Here is your code, just copy-paste and run (the changes are between thick lines ■■■■■■■■■■■■■■■■■■■■■■■■■■■■):
<?php
if ( isset( $_FILES['filesToUpload'] ) )
{
$total = count($_FILES['filesToUpload']['name']);
$succes = [];
$errors = [];
for($i=0; $i<$total; $i++) {
$tmpFilePath = $_FILES['filesToUpload']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "./upimages/" . $_FILES['filesToUpload']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$succes[$_FILES['filesToUpload']['name'][$i]] = true;
}else{
$errors[$_FILES['filesToUpload']['name'][$i]] = true;
}
}
}
//■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
echo "<table border='1'>";
$columns = ceil( sqrt(count($succes) + count($errors)) ); // HOW MANY COLUMNS.
$counter = 0; // COLUMNS COUNTER.
foreach(array_keys($succes) as $suc){
if ( $counter == 0 ) echo "<tr>";
echo "<td>$suc was succesfull</td>";
$counter++;
if ( $counter == $columns ) // IF ROW WAS FILLED
$counter = 0; // INSERT ANOTHER ROW IN NEXT LOOP.
}
foreach(array_keys($errors) as $error){
if ( $counter == 0 ) echo "<tr>";
$counter++;
if ( $counter == $columns ) // IF ROW WAS FILLED
$counter = 0; // INSERT ANOTHER ROW IN NEXT LOOP.
echo "<td>$error failed to upload</td>";
}
echo "</table>";
//■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
} // if ( isset( $_FILES['filesToUpload'] ) )
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="file-input-wrapper">
<button class="btn-file-input">Upload Documents</button>
<input type="file" accept="image/png, image/jpeg" name="filesToUpload[]" id="filesToUpload" multiple="" onChange="makeFileList();" />
<input type="hidden" name="MAX_FILE_SIZE" value="60000000" />
</div>
<p>
<strong>Files You Selected:</strong>
<!--■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■-->
<table id="tableList" border="1">
<tr><td>No Files Selected</td></tr>
</table>
<!--■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■-->
<div class="file-input-wrapper1">
<button class="btn-file-input1">Upload Documents</button>
<input type="submit" value="Upload!" />
</div>
</p>
<style type="text/css">
.file-input-wrapper {
width: 400px;
height: 125px;
overflow: hidden;
position: relative;
}
.file-input-wrapper > input[type="file"] {
font-size: 200px;
position: absolute;
top: 0;
right: 0;
opacity: 0;
}
.file-input-wrapper > .btn-file-input {
display: inline-block;
width: 400px;
height: 125px;
}
.file-input-wrapper:hover > .btn-file-input {
background-color: #aaa;
}
.file-input-wrapper1 {
width: 400px;
height: 125px;
overflow: hidden;
position: relative;
}
.file-input-wrapper1 > input[type="submit"] {
font-size: 200px;
position: absolute;
top: 0;
right: 0;
opacity: 0;
}
.file-input-wrapper1 > .btn-file-input1 {
display: inline-block;
width: 400px;
height: 125px;
}
.file-input-wrapper1:hover > .btn-file-input1 {
background-color: #ffff00;
}
button {
font-size: 26px;
}
</style>
<script type="text/javascript">
function makeFileList() {
var input = document.getElementById("filesToUpload");
//■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
if ( input.files.length > 0 )
{ var tbl = document.getElementById("tableList"); // THE TABLE.
var columns = Math.ceil( Math.sqrt( input.files.length ) ); // HOW MANY COLUMNS.
var counter = 0; // COLUMNS COUNTER.
tbl.innerHTML = ""; // DELETE ALL ROWS.
for (var i = 0; i < input.files.length; i++) {
if ( counter == 0 )
var row = tbl.insertRow( -1 ); // -1 = INSERT ROW AT END OF TABLE.
var cel = row.insertCell( -1 ); // -1 = INSERT CELL AT END OF ROW.
cel.innerHTML = input.files[i].name; // DISPLAY FILE IN CELL.
counter = counter + 1;
if ( counter == columns ) // IF ROW WAS FILLED
counter = 0; // INSERT ANOTHER ROW IN NEXT LOOP.
}
}
//■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
}
</script>
Edit : now there's another table for the UPLOADED files, also the original list of files was removed.

Categories

Resources