How to open images in a separate window? - php

I have a table below where it lists each image(s) for each question.
<table id="tableqanda" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th width="5%" class="questionno">Question No.</th>
<th width="11%" class="image">Image</th>
</tr>
</thead>
</table>
<div id="tableqanda_onthefly_container">
<table id="tableqanda_onthefly" cellpadding="0" cellspacing="0">
<tbody>
<?php
foreach ($arrQuestionId as $key=>$question) {
echo '<tr class="tableqandarow">'.PHP_EOL
echo '<td width="5%" class="questionno">'.htmlspecialchars($arrQuestionNo[$key]).'</td>' . PHP_EOL;
echo '<td width="11%" class="imagetd">';
if (empty($arrImageFile[$key])) {
echo ' ';
} else {
echo '<ul class="qandaul"><li>';
echo implode("</li>\n<li>", array_map(function($imgitem){
return htmlspecialchars($imgitem);
}, $arrImageFile[$key]));
echo '</li></ul>';
}
echo '</td>';
echo '</tr>'.PHP_EOL;
}
?>
</tbody>
</table>
</div>
Now at the moment it just lists the image file names in a bullet point list. But what I want to do is that I want to set each file as a hyperlink so that if the user clicks on an image link, it will display that image in a separate page (a separate window will open up) displaying the image itself
My question is how can this be done, what are the following steps I need to do? If somebody can show me how to code it step by step then I can use it for audios and videos as well.
Thanks

Okay, I've been thinking about what you want to do and I think you want to show a list of images as thumbnails or something, and then click an image and show it (within your layout) on a new page (previewimage.php).
You have a lot of options... but they all boil down to passing some information through the URL (example.com/previewimage.php).
First, let's examine 2 typical ways to pass information through an URL
$_GET Request
Sometimes you'll see a website pass add information to a URL, like
example.com/previewimage.php?var=xxx
This allows you to pass some information to your PHP script via the $_GET superglobal.
Htaccess
If you want to get kind of fancy, you can use htaccess to make a clean URL
RewriteRule ^([a-zA-Z0-9]+)/$ previewimage.php?var=$1
This will let you have an URL like example.com/xxx and the server will act like you went to example.com/previewimage.php?var=xxx.
Now that you know how to hand information off to the url, we can look into some methods for using the $_GET['var'] to show the image.
The easiest approach is to simply pass the name of the file... for this example let's call it example.png.
If you're using the basic $_GET Request method above, you would have an URL like example.com/previewimage.php?var=example.png.
Then, in previewimage.php, you simply do something like
<img src="<?php echo $_GET['var'] ?>"/>
This will output
<img src="example.png"/>
However, this is not a very safe method, as anyone can load anything they want. A better option might be using an array or a database, and then passing a key of some sort and retrieving the filename.
I think this will set you on the right path (and I hope it answers your question).

Assuming this question is how to open a link in a new tab.
Surround whatever you like, image in this case, with this.
<img src="/linktoimage.png" alt="my image">

Here is a sample of how this could be done. Just made edits to the inner "If else" loop
Replace YOUR_BASE_URL_FOR_IMAGES_HERE_ENDING_WITH_A_DASH with the directory path of the images on server.
if (empty($arrImageFile[$key])) {
echo ' ';
} else {
echo '<ul class="qandaul"><li>';
echo implode("</li>\n<li>", array_map(function($imgitem) {
return '' . htmlspecialchars($imgitem) . '';
}, $arrImageFile[$key]));
echo '</li></ul>';
}

Related

Hyperlinked and creating a HTML Page that is nested in a table

So I have a html table that is automatically generated after passing a query to my database. I want to create a hyperlink within my html table to a page that will pull more detailed information from a Second Table.
I was thinking of using the Tablecell creator that pulls from the First Table, and modifying so that it would encompass the table's contents with hyperlink tags. I was thinking it would look like this.
foreach(new TableRow(new AutoArrayMaker($stmt->fetchAll()) as $rowend => $row){
echo <a href = "the reusable HTML Page">;
echo $row;
echo </a>;
}
Is my idea sound from a coding standpoint?
Firstly, echo's need to be in quotation marks " So that code wouldn't fire.
There are a few ways you can output HTML. The first is using echo's:
echo "Google";
Notice how I put a back-slash before hand? This is what is known as an escape. This puts the character after into a letter depending on what it escapes to. See php docs: http://php.net/manual/en/regexp.reference.escape.php (as my description of it was poor)
The other option would be to run out of php then join back on so to speak:
<?PHP
foreach(new TableRow(new AutoArrayMaker($stmt->fetchAll()) as $rowend => $row){
?>
<a href="abc">
<?PHP echo $row; ?>
</a>
<?PHP
}
However, this is not advised.
Edit:
Also, you can make your own table very simply:
<table>
<?PHP
foreach($stmt as $row){
?>
<tr>
<td>
<a href="abc"><?PHP echo $row[id]; ?>
</td>
</tr>
<?PHP
}
?>
</table>
See https://www.w3schools.com/html/html_tables.asp for more info.

strange thing happens when php displaying in html by form actions

First, I got a html file containing code like this:
<form action="Journey.php" method="POST">
<select name = "Startpoint">
<optgroup label = "Start point">
<option value = "GrimesDyke">GrimesDyke</option>
<option value = "SeacroftRingRoad">SeacroftRingRoad</option>
......
this part work fine, it calld the Journey.php file and pass the right data, i use these data to perform php calculations and want it to be displayed in table format like this
echo "<table id = 'Journey' border='1' style='border-collapse:
collapse;border-color: silver;'>";
echo "<tr style='font-weight: bold;'>";
echo "<td width='150' align='center'>Stops</td>";
echo "</tr>";
foreach ($StopRow as $row)
{
echo '<td width="150" align=center>' .$row. '</td>';
echo '</tr>';
}
in my eclipse-php IDE, this worked just fine, however, when it come to the browser... well, there is a table on display.....along with half of my php code.....like the picture below
the thing is, before i put my php code in the html body tag, it works well....please show me how can i make it right...thank you
If PHP is enabled & working then :
It is possible that you have a ?> at that point in code. Just search
for it, you should find it. Remove it.
It may also be cause if you are accessing the file directly(by file path on the browser),
Use : http://localhost/index.php
Otherwise it may be a config problem and hence the question a duplicate : this answer

Make entire row clickable

I am trying to make the entire row of a table clickable. I have looked at a bunch of tutorials and they all seem pretty simple but I can't seem to get it to work. I tried DoNav and that didn't work, the simple onclick attribute doesn't work, what am I doing wrong? I am using mysql, php, and html. Thank you for your help!
echo '<table>';
echo '<tr>';
echo '<th>Name</th><th>Checked In?</th><th>ID</th>';
echo '</tr>';
while($row = $CheckedIn->fetch_assoc()){
echo '<tr onmouseover="ChangeColor(this, true);" onmouseout="ChangeColor(this,false);" onclick="document.location="www.engineering.us/gena/details.php";">';
echo '<td align="left">';
echo $row['ChildName'];
echo '</td>';
echo '<td align="center">';
;
echo $row['checkedin'];
echo '</td>';
echo '<td align="center">';
echo $row['P_Id'];
echo '</td>';
echo '</tr>';
}
echo '</table>';
onclick="document.location="www.engineering.us/gena/details.php";"
this should be
onclick="document.location='www.engineering.us/gena/details.php';"
Also another tip, you have more HTML than php, so it is better to use multiple php tags rather than echo called many times. That way it would be little easier to find such mistakes.
Edit
You should also escape the apostrophe in case you are still going with php
Picking up from what georoot said, use PHP within your HTML. It makes the markup a lot more readable and usually allows your program to add syntax highlighting, making it easier to read. I've added two additional classes ("js-table" and "table-tr") which I'll explain in a bit. Another important point is that the URL is in a new attribute on the table row: data-url.
<table class="js-table">
<thead>
<tr>
<th>Name</th>
<th>Checked In?</th>
<th>ID</th>
</tr>
</thead>
<tbody>
<?php while ($row = $CheckedIn->fetch_assoc()): ?>
<tr class="table-tr" data-url="http://www.engineering.us/gena/details.php">
<td><?php echo $row['ChildName']; ?></td>
<td><?php echo $row['checkedin']; ?></td>
<td><?php echo $row['P_Id']; ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
The "table-tr" class allows us to target the table rows in CSS. There is no need to use JavaScript for something so simple. Even changing the colour of the text within the table cell is very easy in CSS. This technique has the other advantage that it can be easily changed without having to modify any HTML, PHP or JavaScript - it's a purely stylistic thing.
.table-tr:hover {
background-color: red;
}
Finally, since you're using jQuery, we can take advantage of that new "js-table" class. The "js-" prefix states that the class is used for binding functionality and it should not be styled. This script simply bind a click event to the table that listens out for a user clicking on a table row with the data-url attribute. When that happens, the page is re-directed (using window.location instead of document.location - it may work either way, but I've always used window.location) to that URL. This allows you to change the URL later on or change it per row without having to change any of your JavaScript.
$(function () {
$(".js-table").on("click", "tr[data-url]", function () {
window.location = $(this).data("url");
});
});
I hope that helps.
Consider using the following code:
$("#Table tr").click(function () {
$(this).addClass('selected').siblings().removeClass('selected');
var value = $(this).find('td:first').html();
window.location.href = "url";
});
Where Table is the your table name and url is the address you want to navigate to
I think you should try to do that with JQuery.
HTML
<tr class="table-tr"></tr>
JQuery
$('.table-tr').on('click', function(){
window.location = "your url here";
});
Please Change your code with this
<tr onclick="window.location.href=www.engineering.us/gena/details.php">

$_GET not working when trying to view php image in a lightbox style

I have something that im currently working on, however it appears that the $_GET doesn't completely work.
I have a JavaScript light box that brings up an image in a little window, this works however i can only guess that it is using the same URL over and over again.
However when i view the source for the page (and even click one of the links in the source) it will display the correct data.
But the lightbox only seems to display the first image.
This is the JavaScript
<script>
//Checkes if any key pressed. If ESC key pressed it calls the lightbox_close() function.
window.document.onkeydown = function (e)
{
if (!e){
e = event;
}
if (e.keyCode == 27){
lightbox_close();
}
}
</script>
<script>
//This script makes light and fade divs visible by setting their display properties to block.
//Also it scrolls the browser to top of the page to make sure, the popup will be on middle of the screen.
function lightbox_open(){
window.scrollTo(0,0);
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
}
</script>
<script>
//This makes light and fade divs invisible by setting their display properties to none.
function lightbox_close(){
document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none';
}
</script>
I wont show the CSS i dont think thats relivant (If someone wants it then ask away)
The relevant part that creates the links is this, its part of a ForEach statement all PHP
$i = 0;
foreach ($nrows as $nrow)
{
$id = $nrow['id'];
$rid = $nrow['RaidID'];
$bid = $nrow['BossID'];
$normal = $nrow['NormalKills'];
$heroic = $nrow['HeroicKills'];
$boss = substr($nrow['BossName'], 0, 3);
$p1 = $id + $bid.".php";
$image = $boss . $p1;
#echo $image;
echo $bid;
if ($oid != $rid)
{
$i = 0;
}
if ($i == 0) {
?><td style="width: 176px;"><center><b><?php echo $nrow['raid']; ?> </b></center></td> </tr><?php
$i++;
}
?><tr><td style="width: 176px;"><div align="left"><?php echo $nrow['BossName']; ?><div id="light"><img src="bossdata/template.php?boss=<?php echo $bid;?>"></a></div><div id="fade" onClick="lightbox_close();"></div>
</div>
<?php
if ($heroic == 0)
{
if ($normal > 0)
{
echo '<img src="images/whiteskull.png" align="right" alt="Normal Kill">';
}
else
{
echo '<img src="images/redx.png" align="right" alt="Not Killed">';
}
}
else
{
echo '<img src="images/redskull.png" align="right" alt="Normal Kill">';
}
?>
</td></tr><?php
$oid = $id;
}
Now this all works, and it actually displays an image with data, however no matter what link i click the boss data is always from the first one on the list.
To me this means that the data is getting through, and reaching the the right parts on image so its "Working", but all the links do the same thing and show the same data :(
*Removed last code Bulk
You have multiple div with the same ID "light" since you create them in a foreach loop.
<div id="light">
Your function lightbox_open() opens all the divs that have id "light".
document.getElementById('light').style.display='block';
That's why you always see the first lightbox. Because the others are behind the first one.
you should try something like this :
function lightbox_open(elem){
window.scrollTo(0,0);
elem.getElementByClass('light').style.display='block';
elem.getElementByClass('fade').style.display='block';
}
And change this :
<a href="#" onclick="lightbox_open();">
By this :
<a href="#" onclick="lightbox_open(this);">
And replace id by class in your div definition :
<div class="light">
$_GET is working correctly in your code.
The issue is in the way you are combining JavaScript and PHP in the second code box. First, all of your divs have the same ID: "light" which is wrong because they all IDs are meant to be unique within the HTML document. You need to identify them uniquely, for example appending the BossID to them.
After identifying each div uniquely you'll have to edit lightbox_open and lightbox_close so they can receive the BossID of the divs that you want to show and hide.

How to execute PHP and SQL sessions inside Ajax?

I've been asking similar questions here today, but I'm seeing I think the issue is with how I am calling my data?
I'm trying to replace a nav bar with ajax that will load contents into a div.
The nav bar is this:
<ul>
<li>Monthly</li>
<li>Daily</li>
<li>Admin</li>
<li>Help</li>
</ul>
Then I have this to replace the div:
<div id="targetDiv"></div>
the getData function is an innerHTML request:
<script language = "javascript">
function getData(dataSource, divID)
{
$.ajax({
url: dataSource,
dataType: 'html',
success: function(data) {
$('#' + divID).html(data);
}
});
}
</script>
When I click the nav links, the HTML loads into the div, but the contents of my include files also contain PHP functions and jQuery that needs to execute when being loaded and they are just ignored. I've seen this question asked a lot here, but these seem to only relate to jQuery?
To be clear, when I click the nav links, I get a 200 OK in firebug console, but only HTML is coming back and populating div.
Here is my most recently cleaned include file with changes from Jonathan's suggestions. At this point, I am getting output up the the </tr> after the help button (line 15) but no output past that...
<?php
session_start();
?>
<table width='100%' border='0'>
<tr class='twentyfivepxheight'><td></td></tr>
<tr>
<td width='40%' valign='top'>
<div class='left_agenda_items'>
<table width='80%' align='center' border='0'>
<tr class='twentyfivepxheight'>
<td align='left' class='title5 bottompadding unselectable'>Daily Agenda<a href="javascript:void(0)" class="supernote-click-note1">
<img src="/images/help-sm.jpg" alt="Help Button" /></a>
</td>
</tr>
<?php
$numric_time = getNumericTime($_SESSION['userData']['timezone']);
$query = "SELECT * FROM events WHERE date(convert_tz(StartDate,'+00:00','". $numric_time."'))='$currentDate' AND UserID='" . $_SESSION['userData']['UserID'] ."' ORDER BY StartTime";
$result = mysql_query($query);
if(mysql_num_rows($result))
{
while($row = mysql_fetch_assoc($result))
{
$eventID = $row['EventID'];
$eventName = $row['EventName'];
$startDate = $row['StartDate'];
$description = $row['Description'];
$assignedTo = $row['AssignedTo'];
$PTLType = $row['PTLType'];
$parentEventID = $row['ParentEventID'];
$textclass = "greentext unselectable";
$text = "Main event";
//$url = SITE_URL ."/agenda-view-event.php?eventID=$eventID&date=$currentDate&day=$i&type=A&date=$currentDate";
$url = SITE_URL ."/agenda-view-event.php";
if($PTLType == 2) // To do's
{
//$divRed[] = $eventID;
$url = SITE_URL ."/agenda-view-timeline.php";
$textclass = "redtextDaily unselectable";
$text = "To do";
$html_todos .= '
<tr id="redtext' . $eventID . '">
<td id="rowbox'.$eventID.'" class="'. $textclass . '" width="30%" onclick="get_event_popup(\'' . $url . '\', \'agendaViewDiv\', \'agendaLoader\', \'eventID='.$eventID.'\', \'parentEventID='.$parentEventID.'\', \'type=A\', \'date='.$currentDate.'\');setbgagendabox(\''.$eventID.'\');return false">
' . $eventName . ' - (' . $text . ')
</td>
</tr>';
}
elseif($PTLType == 3) //Completed
{
//$divBlue[] = $eventID;
$url = SITE_URL ."/agenda-view-timeline.php";
$textclass = "blueTextDaily unselectable";
$text = "Completed";
$html_completed .= '<tr id="bluetext' . $eventID . '"><td style="display:none;" id="rowbox'.$eventID.'" class="' . $textclass . '" width="30%" onclick="get_event_popup(\'' . $url . '\', \'agendaViewDiv\', \'agendaLoader\', \'eventID='.$eventID.'\', \'parentEventID='.$parentEventID.'\', \'type=A\', \'date='.$currentDate.'\');setbgagendabox(\''.$eventID.'\');return false">' . $eventName . ' - (' . $text . ')</td></tr>';
} else { //main events
//$divMainEvent[] = $eventID;
$html_main_events .= '<tr id="mainEvent' . $eventID . '"><td id="rowbox'.$eventID.'" class="' . $textclass . '" width="30%" onclick="get_event_popup(\'' . $url . '\', \'agendaViewDiv\', \'agendaLoader\', \'eventID='.$eventID.'\', \'date='.$currentDate.'\', \'day='.$i.'\', \'type=A\', \'date='.$currentDate.'\');setbgagendabox(\''.$eventID.'\');return false">' . $eventName . ' - (' . $text . ')</td></tr>';
}
}
echo $html_main_events . $html_todos . $html_completed;
} else {
?>
<tr>
<td>
<span class="a_dateformat">You have no agenda items due today!</span>
</td>
</tr>
<?php
}
?>
</table>
</div>
<input type="hidden" id='lastselected' value='' style="" />
</td>
<td class='verticalborder'> </td>
<td width='59%' valign="top" align="center">
<div id="agendaLoader" style="display:none;">
<img src="images/ajax-loader-orange.gif" alt="wait" />
</div>
<div id="agendaViewDiv" style="display:none;"></div>
</td>
</tr>
<tr>
<td colspan="3">
</td>
</tr>
</table>
But see how I commented out the jQuery to make it work?
If that is not commented out, I don't get any output. The problem is that I need that jQuery to properly build the page.
For anybody who stumbles across this "answer," please note that it was not intended to be so broken-up. Each portion of this answer was added at a later date following exchanges with the OP in the comments. The items on top are the latest additions whereas the furthest items down were earlier additions.
Jonathan Sampson
Call to undefined function
Because this page is typically included, and not called directly, there may be some things that won't be available when requested. You indicated in the comments that the function getNumericTime() doesn't exist, and is causing an error.
You'll want to make it exist, but you don't want to just redeclare it, or else that will cause problems for you when you request this page as an include-file to another page that already has that function. So what you'll want to do is check whether the function exists, and create it if it doesn't.
if (!function_exists("getNumericTime")) {
function getNumericTime($foo) {
// get the function logic and place it here
}
}
Now, when you call the include-file directly, the function will be created if it doesn't exist. When you call the old-fashioned way, with this file being included, the if-statement will simply skip pass the new function declaration, since the function already exists.
If this function exists within a functions file, you can include it, but be sure to use include_once() instead of include(). include_once() will not include the file if it's already be included once before. Given the fact that this page is occasionally in another environment where the functions include has already taken place, we want to be sure not to include it again, so we use the include_once() method.
Missing connection and selection...
You're attempting to perform queries, yet there's no database connection on this page. There is also no mysql_select_db() call to select from a specific database. Without these, your queries won't succeed and your data won't be returned.
// Our connection to mysql
$conn = mysql_connect($host, $user, $pass) or die(mysql_error());
// Which database we're using
mysql_select_db($dbname) or die(mysql_error());
Once that connection is made (within index.php, for example) we could do an include:
include("foo.php");
The contents of foo.php now have a connection opened so they can perform queries, call stored-procedures, etc. This is only the case because it's being included into a page that has an open-connection.
If we were to access foo.php directly, which is what you're doing with your ajax-request, we wouldn't get the results we want, because foo.php doesn't provide its own database connection - it depends on index.php (which it is often times included into) to provide that connection.
From PHP to HTML to PHP...
One thing that often times causes problems outputting HTML progressively through a PHP Script. Often times you'll see numerous echo statements followed by HTML strings that are littered with back-slashes to escape certain output. Not only is this tedious to write, but it's a pain to search when problems arise. HTML rarely needs to be within PHP. When you need to output HTML, get out of your PHP tags for a moment:
<?php
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result)) {
while ($row = mysql_fetch_assoc($result) { ?>
<tr>
<td>Data Here</td>
<td><?php print $row["foo"]; ?></td>
</tr>
<?php }
} else { ?>
<tr>
<td>No records found</td>
</tr>
<?php }
?>
Notice how it's easier to tell when my HTML is wrong someplace, and it's easy to jump from writing markup to writing PHP. Ideally, you wouldn't even do it this way, but this is an improvement over what you currently have.
Properly using $_SESSION
After giving a look at your code, I noticed that you're calling values out of $_SESSION, or trying to at least. You can only do this if you have called session_start() at the top of the page. Your code lacks this, which may be the reason you're not getting anything back as an integral part of your SQL Queries is missing. Add the following to the very top of your script:
<?php session_start(); ?>
PHP Code Not Executing?
If your PHP isn't executing, there's a problem with the script or the server, but not with jQuery. Check to make sure you have both the opening and closing PHP tags in the script you're requesting:
<?php
/* and */
?>
Simplifying things
You could simplify and clean up your code a bit too. First of all, let's create a new nav-bar:
<ul id="nav">
<li>Index</li>
<li>About</li>
<li>Contact</li>
</ul>
Note how I'm linking directly to the files, and not using any javascript to cancel out my clicks. This way, when a user stumbles onto my site without javascript enabled, they're not faced with a broken website, they can still get around.
Without interspersing javascript in our HTML, we'll bind up some logic to these nav-links:
$(function(){
// Attach logic to all links
$("#nav a").click(function(e){
// Prevent link from redirecting page
e.preventDefault();
// Load next page into #targetDiv
$("#targetDiv").html("").load($(this).attr("href"));
});
});
And that's it. You're done.
This answer is in response to the follow part of the question:
When I click the nav links, the HTML
loads into the div, but the contents
of my include files also contain PHP
functions and jQuery that needs to
execute when being loaded and they are
just ignored.
Note that the JavaScript that gets returned from XMLHttpRequestObject.responseText will not execute when inserted into the DOM text with innerHTML as you are doing.
You may want to check the following Stack Overflow post for a couple of solutions around this issue:
Can scripts be inserted with innerHTML?
However, if you are using jQuery, you can replace all the code in getData() with the following:
function getData(dataSource, divID)
{
$.ajax({
url: dataSource,
dataType: 'html',
success: function(data) {
$('#' + divID).html(data);
}
});
}
When the jQuery ajax() method is called with the dataType: 'html' option, included script tags are automatically evaluated when inserted in the DOM. You may want to check the following Stack Overflow post for further reading on this:
When loading an html page via ajax, will script tags be loaded?

Categories