Unique Value For Each Button - php

I have two php pages. The first page queries a database and places some data into a form
The second page, grabs the data submited from the previous page and displays the data.
THE ISSUE:
On the second page, the information is displayed in a table. At the end of each row, there is a "information" button that allows the user to click and see more details related to the data in that particular column. For some reason, the information button for every record in the table is holding the value of the first record returned in the database query. In other words no matter what button I click on in the table, it always relates to the first record returned in the query.
I'm hoping someone can help me find a solution to linking each "information" button to each unique record. In other words If I click the info button in row one, it will display the data for the record related to row 1...etc. Here's my code.
PAGE 1
<?php
$query = mysql_query ("SELECT * from cust_data group by cabinet_number ORDER by cabinet_number ASC");
WHILE ($rows = #mysql_fetch_array($query)) {
if (($rows['account_number']=="") &&
($rows['customer_first_name']=="") &&
($rows['customer_last_name']=="") &&
($rows['company_name']=="")) {
echo '<form method="GET" action="cabinet_result_page.php">
<input type="hidden" value="'.$rows['cabinet_number'].'" name="cabinet_number">
<input type="hidden" value="'.$rows['company_name'].'" name="company_name">
<img src="images/bulletpoint_green.png">
<input type="submit" value="'.$rows['cabinet_number'].'" name="'.$rows['cabinet_number'].'" id="submit">
</form>';
} else if ($rows['cabinet_number']!=="") {
echo '<form method="GET" action="cabinet_result_page.php">
<input type="hidden" value="'.$rows['cabinet_number'].'" name="cabinet_number">
<input type="hidden" value="'.$rows['company_name'].'" name="company_name">
<img src="images/bulletpoint_red.png">
<input type="submit" value="'.$rows['cabinet_number'].'" name="'.$rows['company_name'].'" id="submit">
</form>';
}
}
}
PAGE 2:
GRABS THE DATA IN PAGE ONE AND PLACES IT IN A TABLE. WHEN THE 'INFO' BUTTON IS CLICKED, MORE INFORMATION IS DISPLAYED IN A JQUERY POPUP
db_connect();
$cabinet_number = $_GET['cabinet_number'];
$company_name = $_GET['company_name'];
$query = #mysql_query ("SELECT * FROM cust_data WHERE cabinet_number = '$cabinet_number' ");
WHILE ($rows = #mysql_fetch_array($query)) {
echo'<tr>
<td><font size="4">'; echo $rows['account_number']; echo'</font></td>
<td><font size="4">'; echo $rows['customer_first_name']; echo '</font></td>
<td><font size="4">'; echo $rows['customer_last_name']; echo '</font></td>
<td><font size="4">'; echo $rows['company_name']; echo '</font></td>
<td><font size="4">'; echo $rows['cabinet_number']; echo'</font></td>
<td><font size="4">'; echo $rows['key_tag_number']; echo'</font></td>';
if ($rows['switch_and_port1'] =="") {
echo '';
} else if ($rows['switch_and_port1'] !== "") {
echo '<td><font size="4">';
echo '<input type = "image" src= "images/view_details.png" height="16" width="16" class="my_modal_open">', '</font></td>';
}
{
echo '<td><font size="4">'; echo '<input type = "image" src= "images/view_details.png" height="16" width="16" class="my_modal_open">', '</font></td>';
}
echo '</tr>';
echo '<div class="well" style="display:none;margin:1em;" class="my_modal">';
echo '<img src="images/hdc_logo_transparent.png"><br>';
echo '<div style="height:23px; width:100%; background-color:black"> <h4><font color="#FFFFFF">',' ', 'Cabinet: ', $id, '</font></h4></div>';
echo '<p>';
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Power: ', $rows['power_circuit'];
echo '<br>';
echo'<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port1'];
if ($rows['switch_and_port2'] =="") {
echo '';
} else if ($rows['switch_and_port2'] !== "") {
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port2'];
}
if ($rows['switch_and_port3'] =="") {
echo '';
} else if ($rows['switch_and_port3'] !== "") {
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port3'];
}
if ($rows['switch_and_port4'] =="") {
echo '';
} else if ($rows['switch_and_port4'] !== "") {
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port4'];
}
echo '</p>';
echo'</div></form>';
}
echo'<script>
$(document).ready(function() {
$(".my_modal_open").click(function(){
$(this).closest("tr").next(".my_modal").popup({"autoopen": true});
});
});
});
</script>
</body>
</html>';
}

The issue is that you are setting the same id attribute to all the modals (which is invalid HTML markup) and expecting the click handler on the button to figure out which one to open.
UPADTE
Another issue with your markup is that you can't have <div>s as siblings of a table row, it will produce unexpected results as browsers will attempt to fix the markup and rearrange the elements, you could place the divs inside a td or use a second loop to build them.
Now I also did some digging in your popup plugin and I must say it's not very well implemented, I would recommend you look for another one. That being said I did manage to get it working, here's what you need to do:
Set an unique id for each of the modal divs, if you have some sort of id in your database data you can use that, if not then you can set up a counter variable inside the loop:
echo '<div class="well" id="my_modal'.$rows['id'].'">';
Use the same id as the class for the button that should open the modal but add "_open" as a suffix:
echo '<input type = "image" src="images/view_details.png" height="16" width="16" class="my_modal'.rows['id'].'_open">
You can now initialize the popup plugin on your divs and it will automatically assign the open action to the corresponding button:
echo'<script>
$(document).ready(function () {
$("[id^=\'my_modal\']").each(function () {
$(this).popup();
});
});
</script>';
That should fix the modal problem, here's a working demo.
Now I also have a couple observations about your code:
You should avoid the use of inline styles and as I mentioned earlier the <font> tag should be replaced for proper CSS, I would also suggest using CSS padding/margin to add space between words instead of
This type of code:
if ($rows['switch_and_port1'] =="") {
echo '';
} else if ($rows['switch_and_port1'] !== "") {
echo 'SOME CONTENT';
}
can be optimized to just:
if ($rows['switch_and_port1'] !== "") {
echo 'SOME CONTENT';
}
echoing an empty string produces no output whatsoever and there's no need for an elseif

Related

php arrange checkbox values in two columns

I have a form with checkboxes and I want to arrange the checkboxes in two columns instead of one single long column.
How can i split it to two columns?
Here is my code:
if($proceder == True) {
echo "<form name='formulario' method='POST' action='iconizar.php'>";
$iconosm = 0;
$server_groups = $ts3_VirtualServer->serverGroupList();
$servergroups = array();
# En vez de iterar por todos los grupos intenten
foreach($server_groups as $group) {
if($group->type != 1) { continue; }
if(in_array($group["sortid"], $SID_GROUP)) {
$servergroups[] = array('name' => (string)$group, 'id' => $group->sgid, 'type' => $group->type);
}
}
$_SESSION['grupos'] = $servergroups;
foreach($servergroups as $group) {
$miembros = $ts3_VirtualServer->serverGroupClientList($group["id"]);
$estaengrupo = False;
foreach($miembros as $m) {
if($m["client_unique_identifier"] == $client_uid) {
$estaengrupo = True;
}
}
if($estaengrupo) {
$iconosm = $iconosm + 1;
echo '<li><img src="./iconos/icons/'.$group['id']. '.png" alt="" /> ';
echo '<label><input type=checkbox name=grupos['.$group["id"].'] id="'.$group["id"].'" value="'. $group["id"] .'"class="icono" checked >'.$group["name"].'</label><br>';
} else {
echo '<li><img src="./iconos/icons/'. $group['id'] . '.png" alt="" /> ';
echo '<label><input type=checkbox name=grupos['.$group["id"].'] id="'. $group["id"] .'" value="'. $group["id"] .'" class="icono"> '.$group["name"].'</label><br>';
}
}
I'm assuming your have additional code not posted that close your form and li elements, but in any case you can do this using CSS. Set a width on your form (or it's wrapping element that will accomodate two of your li elements, side by side, then set the float property to 'left' for your li tags... Using inline styles, you might echo html that looks like this:
form tag:
<form style="width: 400px;" name='formulario' method='POST'>
li tags:
<li style="width 50%;float: left;">...
If you need your checkboxes to appear first half down the left column, then second half down the write, that will involve some PHP.
Where is your unodered element then change to

jquery Datatables with dialog button

I am trying to utilize a button that will open a dialog based on the specific row that the button is located in. I have attached my code below.
The button is class is dlg-outletpart-btn:
Here is the jquery javascript portion:
<script> /*datatables script function below */
$(document).ready( function () {
$('#table_id_outlets').DataTable();
} );
</script>
<script> /*jquery dialog controls for project detail */
$(function() {
$( ".dlgoutletpart" ).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 500
},
hide: {
effect: "fade",
duration: 700
},
});
$( ".dlg-outletpart-btn" ).click(function() {
var outletID = $(this).attr("data-dlg-outletparts");
$( "#dialog-" + outletID ).dialog( "open" )
});
});
</script>
Here is the html with php:
<body>
<div>
<p>
<h3>Go Back to main page</h3>
</p>
</div>
<div>
<?php
session_start();
require_once('./includes/php/include_master.php');
if ($_SESSION['authenticated'] == "true") {
$id_account = $_SESSION['ID_Account'];
$q = $protoFM['EMGSV'] -> newFindCommand('web_outlets');
$q -> addFindCriterion('id_account', '=='.$id_account);
$r = $q->execute();
if(FileMaker::isError($r)){
if($r->code == 401){
echo "No outlets found.";
}else{
echo "Unknown Error:".$r->code;
}
}else{
}
} else {
echo "You are not logged in.";
}
?>
<?php
foreach ($r->getRecords() as $parts){
$outletID = $parts->getField('ID_Outlet');
$outletData1 = $parts->getField('Image_Data');
$outletData2 = $parts->getField('Image_Data2');
$outletData3 = $parts->getField('Image_Data3');
$outletPart1 = $parts->getField('part1');
$outletPart2 = $parts->getField('part2');
$outletPart3 = $parts->getField('part3');
$outletPart4 = $parts->getField('part4');
$outletPart5 = $parts->getField('part5');
$outletPart6 = $parts->getField('part6');
$outletPart7 = $parts->getField('part7');
$outletPart8 = $parts->getField('part8');
$outletPart9 = $parts->getField('part9');
$outletPart10 = $parts->getField('part10');
echo '<div class="dlgoutletpart" id="dialog-' .$outletParts. '" title="Outlet Parts for '.$outletID.'">';
echo '<p>';
echo '1. '.$outletPart1.'<br>';
echo '2. '.$outletPart2.'<br>';
echo '3. '.$outletPart3.'<br>';
echo '4. '.$outletPart4.'<br>';
echo '5. '.$outletPart5.'<br>';
echo '6. '.$outletPart6.'<br>';
echo '7. '.$outletPart7.'<br>';
echo '8. '.$outletPart8.'<br>';
echo '9. '.$outletPart9.'<br>';
echo '10. '.$outletPart10.'<br>';
echo '</p>';
echo '</div>';
}
?>
<table id="table_id_outlets" class="display">
<thead>
<tr>
<th>Floor</th>
<th>Area Served</th>
<th>Room Number</th>
<th>Outlet Number</th>
<th>Outlet Gas</th>
<th>Outlet Manufacturer</th>
<th>Outlet Model</th>
<th>Outlet Parts</th>
</tr>
</thead>
<tbody>
<?php
foreach ($r->getRecords() as $outlet){
$outletFloor = $outlet->getField('Outet_Floor');
$outletAreaServed = $outlet->getField('Outlet_Area_Served');
$outletRoomNumber = $outlet->getField('Outet_Room_Number');
$outletNumber = $outlet->getField('Outlet_Number_In_Room');
$outletGas = $outlet->getField('Outlet_Gas_Type');
$outletManufacturer = $outlet->getField('Outlet_Manufacturer');
$outletModel = $outlet->getField('Outlet_Model');
echo "<tr>";
echo '<td>' .$outletFloor. '</td>';
echo '<td>' .$outletAreaServed. '</td>';
echo '<td>' .$outletRoomNumber. '</td>';
echo '<td>' .$outletNumber. '</td>';
echo '<td>' .$outletGas. '</td>';
echo '<td>' .$outletManufacturer. '</td>';
echo '<td>' .$outletModel. '</td>';
echo '<td> <button class="dlg-outletpart-btn" data-dlg-outletparts="'.$outletParts.'">Outlet Parts</button>';
}
?>
</tbody>
</table>
</div>
<?php $outlet->getfields('Outlet_Room_Number')?>
</body>
I didn't try to test this and there was a lot of cleanup needed so take this with a grain of salt rather than the exact solution.
Before I get into the explanation, there are a couple of points that need to be made:
Stay on top of your indention levels
Poorly indented code is harder to build in and even harder to troubleshoot.
REMEMBER: what you post online reflects on you as a programmer.
Don't use variables with single letters.
Give your variables proper and descriptive names. Single letter names also make it hard to code and hard to troubleshoot.
If you don't need it, don't write it
This is especially true if you're going to post on StackOverflow asking for help. The place where you had an else clause without any code in it should be stripped out of your question and really should be stripped out of your code. If you don't have any tasks to perform within a clause then don't add it. Add it back in when you actually need it. This goes for the closing and immediately opening of the php element. There's no reason to close one php element if you're going to immediately open another. If this is because your knitting two different sections together for the question then clean it out before you submit it.
So, here's the code you can try. Focus on the parts that I commented on in the javascript. The basic idea is:
Make the table your main selector.
You could make the tr element the main selector and it would still give you the index of the tr in the table, but adding the selector to the table itself means if you programmatically add new rows after the DOM has been rendered the jquery method will work for them as well.
Use the this keyword as a starting point.
this will be the button clicked which will allow you to navigate around.
Leverage jquery's navigation methods, in this case closest().
<html>
<head>
<script> /*datatables script function below */
$(document).ready( function () {
$('#table_id_outlets').DataTable();
});
</script>
<script> /*jquery dialog controls for project detail */
$(function() {
$( ".dlgoutletpart" ).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 500
},
hide: {
effect: "fade",
duration: 700
},
});
// I changed the element selector to the id of the table element.
// This allows you to specify the selector for the 'on' method to apply to all
// tr elements within the given table and then reference their index relative
// to the overall table.
// I'm using `button` for the method's selector because you have only have
// on button in your table so it de-couples your selector from your class name.
$( "#table_id_outlets" ).on('click', 'button', function() {
debugger;
// this: refers to the button that was clicked
// closest: walks up the node hierarchy till it finds a `tr`
// index(): gives you the index of the `tr` within the table.
// Use the index number however you need.
console.log($(this).closest('tr').index());
var outletID = $(this).attr("data-dlg-outletparts");
$( "#dialog-" + outletID ).dialog( "open" )
});
});
</script>
</head>
<body>
<div>
<p>
<h3>Go Back to main page</h3>
</p>
</div>
<div>
<?php
session_start();
require_once('./includes/php/include_master.php');
if ($_SESSION['authenticated'] == "true") {
$id_account = $_SESSION['ID_Account'];
// Note: you can't put a space between your
$query = $protoFM['EMGSV']->newFindCommand('web_outlets');
$query->addFindCriterion('id_account', '==' . $id_account);
$result = $query->execute();
if(FileMaker::isError($result)){
if($result->code == 401){
echo "No outlets found.";
}else{
echo "Unknown Error:".$result->code;
}
}
} else {
echo "You are not logged in.";
}
foreach ($result->getRecords() as $parts){
$outletID = $parts->getField('ID_Outlet');
$outletData1 = $parts->getField('Image_Data');
$outletData2 = $parts->getField('Image_Data2');
$outletData3 = $parts->getField('Image_Data3');
$outletPart1 = $parts->getField('part1');
$outletPart2 = $parts->getField('part2');
$outletPart3 = $parts->getField('part3');
$outletPart4 = $parts->getField('part4');
$outletPart5 = $parts->getField('part5');
$outletPart6 = $parts->getField('part6');
$outletPart7 = $parts->getField('part7');
$outletPart8 = $parts->getField('part8');
$outletPart9 = $parts->getField('part9');
$outletPart10 = $parts->getField('part10');
echo '<div class="dlgoutletpart" id="dialog-' .$outletParts. '" title="Outlet Parts for '.$outletID.'">';
echo '<p>';
// Use an unordered list here
echo '1. '.$outletPart1.'<br>';
echo '2. '.$outletPart2.'<br>';
echo '3. '.$outletPart3.'<br>';
echo '4. '.$outletPart4.'<br>';
echo '5. '.$outletPart5.'<br>';
echo '6. '.$outletPart6.'<br>';
echo '7. '.$outletPart7.'<br>';
echo '8. '.$outletPart8.'<br>';
echo '9. '.$outletPart9.'<br>';
echo '10. '.$outletPart10.'<br>';
echo '</p>';
echo '</div>';
}
?>
<table id="table_id_outlets" class="display">
<thead>
<tr>
<th>Floor</th>
<th>Area Served</th>
<th>Room Number</th>
<th>Outlet Number</th>
<th>Outlet Gas</th>
<th>Outlet Manufacturer</th>
<th>Outlet Model</th>
<th>Outlet Parts</th>
</tr>
</thead>
<tbody>
<?php
foreach ($result->getRecords() as $outlet){
$outletFloor = $outlet->getField('Outet_Floor');
$outletAreaServed = $outlet->getField('Outlet_Area_Served');
$outletRoomNumber = $outlet->getField('Outet_Room_Number');
$outletNumber = $outlet->getField('Outlet_Number_In_Room');
$outletGas = $outlet->getField('Outlet_Gas_Type');
$outletManufacturer = $outlet->getField('Outlet_Manufacturer');
$outletModel = $outlet->getField('Outlet_Model');
echo "<tr>";
echo '<td>' .$outletFloor. '</td>';
echo '<td>' .$outletAreaServed. '</td>';
echo '<td>' .$outletRoomNumber. '</td>';
echo '<td>' .$outletNumber. '</td>';
echo '<td>' .$outletGas. '</td>';
echo '<td>' .$outletManufacturer. '</td>';
echo '<td>' .$outletModel. '</td>';
echo '<td> <button class="dlg-outletpart-btn" data-dlg-outletparts="'.$outletParts.'">Outlet Parts</button>';
}
?>
</tbody>
</table>
</div>
<?php $outlet->getfields('Outlet_Room_Number')?>
</body>
</html>
I didn't test the php portion out, but the jquery definitely works.

AJAX form sending data, PHP form not receiving it

I had this working earlier, but now it doesn't seem to want to pick up the data. It's possible something changed when I was trying to make it stop refreshing the page.
The form submits, but only for certain links. However the data gets sent across as normal. It's extremely strange.
This is the page the data is being sent to. Right now it just accepts the data and posts it for testing. "Text" shows but nothing else.
<?php
$ship_id = $_POST['transfer_ship'];
$char_id = $_POST['transfer_character'];
$pos_id = $_POST['transfer_position'];
$requested_by = $_POST['transfer_player'];
echo 'Success';
echo $ship_id;
echo $char_id;
echo $requested_by;
echo $pos_id;
echo $char_owner;
echo 'Text';
This is the form it's being sent from. It's part of a PHP UL series that's running. For the first result, the jQuery fires, I get the "Success" alert. For any of the other li links the data apparently gets sent (I use the F12 dev tools in Chrome, under Network, to see the header) but the page above either doesn't receive it or doesn't do anything with it.
jQuery:
<script type="text/javascript" src="../fancybox/jquery.fancybox.js?v=2.1.3"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".fancybox").fancybox();
});
</script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#transfer').ajaxForm(function() {
alert('Success!');
});
});
</script>
Form and UL:
<ul>
<?php
while(list($key, $val) = each ($arrayresult))
{
echo '<a href="#inline' .$val. '" class="fancybox"><li style="padding: 2px; margin: 0px; list-style: none;">';
echo '<img src="../images/profilepics/'.$charpic.'" style="float: right; padding-left: 10px; width: 40px;" />';
echo '<h2>'.$val.' Position</h2>';
echo '<p>Click here to apply for this position.</p>';
echo '</li></a>';
echo '<div id="inline' .$val. '" style="display:none;">';
echo '<h1>Request Character Transfer</h1>';
echo '<hr>';
echo '<form id="transfer" action="TransferRequest.php" method="post">';
echo '<label for="transfer_character">Character to Transfer</label>';
echo '<select id="transfer_character" name="transfer_character">';
echo '<option value="">Select Character</option>';
$request_character_query = "SELECT * FROM character_database WHERE character_active ='1' AND user_id = $user_id ORDER BY character_firstname DESC";
$request_character_result = mysqli_query($mysqli, $request_character_query);
/*** loop over the results ***/
foreach($request_character_result as $charrow)
{
/*** create the options ***/
echo '<option value="'.$charrow['character_id'].'">'. $charrow['character_firstname'] . " " . $charrow['character_surname'] . '</option>'."\n";
}
echo '</select>';
echo '<p>Applying for the '.$val.' position on the '.$shipname.'</p>';
echo '<p>If this is correct, please submit below</p>';
echo '<input type="hidden" value="'.$val.'" name="transfer_position">';
echo '<input type="hidden" value="'.$ship_id.'" name="transfer_ship">';
echo '<input type="hidden" value="'.$user_id.'" name="transfer_player">';
echo '<input value="Submit Request" type="submit" class="styled">';
echo '</form>';
echo '</div>';
}
?>
</ul>
I figured it out! I have my htaccess file removing the .php extension, but I had .php on the redirect link for ajax. So it was hitting the .php page then redirecting WITHOUT the POST data.

Show alert with the content of a Database selection

I am very new to JavaScript what is related to it.
I have a set of dynamic rows and corresponding columns to those rows. In one column I have a button. When I click on it, it displays the results of a select query in another page based on the Posted Competence_ID.
The query works fine and I get correct results when I click on the button. However, what I would like to do now, is to display that message in an alert when the button is clicked and stay on the same page rather than opening a new tab..
Here is the relevant HTML code that shows the table I use:
echo "<table border='1' id='mycompstable' class='sortablee' cellpadding='0' cellspacing='0'>";
echo "<tr><th>ID</th><th>Competence Group</th><th>Competence Class</th><th>Competence Description</th><th>Own Evaluation</th><th>Manager's evaluation from last year</th><th>Target levels</th><th>Gap</th><th>Action</th><th class='unsortable'>Action ready target </th></tr>";
foreach($descs as $compi){
echo "<tr>";
echo "<td>".$compi['Competence_ID']."</td>";
echo "<td><p style='text-align: center;'>".$compi['Competence_Group']."</p></td>";
if(isset($compi['Competence_class'])){echo "<td>".$compi['Competence_class']."</td>";}else echo "<td><p style='text-align: center;'>-</p></td>";
echo "<td>".$compi['Competence_Description']."</td>";
echo "<td class='evaluation'>";
echo "<select class='ownlevelselect' id='ownlevelselect-.".$compi['Competence_ID']."' name='level-".$compi['Competence_ID']."' >";
if (isset($compi['ownlevel']) && $compi['ownlevel']!= '' && !empty($compi['ownlevel']) && $compi['ownlevel']!= 0) {
echo "<option selected value='".$compi['ownlevel']."' selected='selected'>".$compi['ownlevel']."</option>";
}
echo "<option value='' >--</option>";
echo "<option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option>";
echo "</select>";
echo $compi['ownlevel'];
echo '<a test="'.$compi['Competence_ID'].'" onClick="showLevels('.$compi['Competence_ID'].');" target="_blank" href="'.INDEX.'?categ='.$_GET['categ'].'&action='.$_GET['action'].'&subaction=viewlevels'.'&levels='.$compi['Competence_ID'].'">';
echo '<img class="linkki" src="'.KUVAT.'paivita.gif" alt="'._("tiedot").'" title="'._("Click to view the description of each level?").'"/></a>';
echo "</td>";
Here is the code to retrieve the data:
function fetchlevels($Competence_id){
$this->query="SELECT * FROM levels WHERE comp_id=".$_REQUEST['levels'];
$tulos=$this->suoritaKysely();
return $tulos;
}
And here is the page that I want to show in the message:
$levels=$this->levels;
$comp=$this->compdesc;
echo "Levels explanation for the competence:".$comp['Competence_Description']."<br>";
echo "Level 1 = ".$levels[0]['lvl1'];
echo "<br>"."level 2 = ".$levels[0]['lvl2'];
echo "<br>"."level 3 = ".$levels[0]['lvl3'];
echo "<br>"."level 4 = ".$levels[0]['lvl4'];
echo "<br>"."level 5 = ".$levels[0]['lvl5'];
echo "<br><br>";
echo '<input type="button" value="close" window onclick="window.close();">';
?>
Any kind of help would be very much appreciated
Here is a Ajax simulation in jsfiddle
http://jsfiddle.net/ncubica/Umxjb/
HTML
<i style='display:none' id="loadingPopup">Loading</i>
<table>
<tr>
<td data-id="td1"> row 1</td>
</tr>
<tr>
<td data-id="td2"> row 2</td>
</tr>
<tr>
<td data-id="td3"> row 3</td>
</tr>
</table>
javascript
$("table").on("click", function(event){
var $target = $(event.target);
if($target.is("td")){
var id = $target.attr("data-id");
makeAjax(id);
}
});
//simulating ajax
function makeAjax(id){
//you will have to use ajax an retrieve you json format
//i will simulate ajax only
$("#loadingPopup").show();
var _json = { id : id, value : "some value", description : "some description"};
setTimeout(function(){response(_json)}, 1000);
}
function response(_json){
$("#loadingPopup").hide();
alert(_json.id + " - " + _json.value);
}
CSS
table{font-family:arial; font-size:12px; width:100%}
table tr td{border-bottom:1px solid #CCC; padding:10px;}
Just an example based on the given info!
echo '<a onClick="showLevels('.$compi['Competence_ID'].');">';
echo '<img class="linkki" src="'.KUVAT.'paivita.gif" alt="'._("tiedot").'" title="'._("Click to view the description of each level?").'"/></a>';
Javascript/jQuery/Ajax
function showLevels(comp_id)
{
$.ajax({
type: "GET",
url: "process_file.php?comp_id="+comp_id,
success: function (result) {
alert(result);
}
});
}
process_file.php
<?php
//Your database Config.
$comp_id=$_REQUEST['comp_id'];
$this->query="SELECT * FROM levels WHERE comp_id=".$comp_id;
$tulos=$this->suoritaKysely();
//Proper Output Actions
$levels=$this->levels;
$comp=$this->compdesc;
echo "Levels explanation for the competence:".$comp['Competence_Description']."<br>";
echo "Level 1 = ".$levels[0]['lvl1'];
echo "<br>"."level 2 = ".$levels[0]['lvl2'];
echo "<br>"."level 3 = ".$levels[0]['lvl3'];
echo "<br>"."level 4 = ".$levels[0]['lvl4'];
echo "<br>"."level 5 = ".$levels[0]['lvl5'];
echo "<br><br>";
?>

Performing different actions on dynamically generated buttons. PHP

I am working on a PHP Gallery application, and need some help here. Actually I have a page where images from a specific directory are displayed directly. With each one of the images displayed there is a dynamically generated submit button that will be used to delete respective images separately.
Every image has its own submit button, that will be used to delete that image. Being new to php I need some method that can be called to delete only that image from the actual or physical directory.
There is a similarity between image and button that I have coded it such that every image and its respective button has names such as "img_1" and its button is "del_1".
<form id="albumGallery" name="albumGallery" method="POST">
<?php
$dir = htmlspecialchars($_GET["p"]) . "/";
$imgs = array();
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!is_dir($file) && preg_match("/\.(bmp|jpe?g|gif|png)$/", $file)) {
array_push($imgs, $file);
}
}
closedir($dh);
} else {
die('cannot open ' . $dir);
}
$i=0;
echo "<div id='images'>";
foreach ($imgs as $idx=>$img) {
//$class = ($idx == count($imgs) - 1 ? ' class="last"' : '');
echo '<table style="float: left; border: 1px solid #EFEFEF; border-radius: 5px; padding: 5px; margin: 5px;"><tr><td><a href="'. $dir . $img .'" rel="example_group" ><img src="' . $dir . $img . '" alt="' . $img . '" id="'. "img_" . $i .'"/>
</a></td></tr><tr><td><input type="submit" class="ctrlDelete" value="" id="'. "del_" . $i .'"/></td></tr></table>';
$i++;
}
echo "</div>";
?></form>
So, I need to make a method so that each button deletes its respective image and the form is posted back to self.
For your issue, it is better to use anchors. You can style them as pseudo-buttons, if you want. Then just generate links like delete.php?id=23, which will execute the appropriate deletion script with $_GET argument passed.
Below is the very simple implementation:
<table>
<tr>
<td>Title</td>
<td>Image</td>
<td>Actions</td>
<tr>
<?php
foreach ($table as $row)
{
echo "<tr>";
echo "<td>".$row['title']."</td>";
echo "<td>".$row['image']."</td>";
echo "<td>";
echo "<a href='delete.php?id=".$row['id']."'>Delete</a>";
echo "<a href='edit.php?id=".$row['id']."'>Edit</a>";
echo "</td>";
echo "</tr>";
}
?>
</table>
delete.php and edit.php should contain the following code at the very end:
<?php
header("Location: http://www.example.com/");
?>
#Edward Ruchevits
Thanks for your help :D,
I did not use the header(); method but used the javascript's settimeout(); to redirect my page. Here is my code...
<script type="text/javascript">
setTimeout("window.location = '<?php echo $_SERVER['HTTP_REFERER'] ?>'", 1);
</script>
<?php
$path = htmlspecialchars($_GET["p"]);
unlink($path);
?>
I suggest adding the form tag inside your foreach loop and post each of those forms to self. Each form can simply include a hidden field with the image ID. Then each time the page loads, you can simply check the $_POST variable for the image and delete that before serving up your page.
Alternately, you might consider using checkboxes next to the images - then one form and one submit button can action multiple deletions in one - far more efficient in my opinion.
Hope this helps!

Categories