PHP, mulitchoice FORMS, how to pass variable selected in form, - php

and show form based on that variable in single page, without pressing SUBMIT or buttons?
i have loop for fill 'select' in FORM
echo '<select name="inne_zad" class="cfpa" width="400" style="width: 400px" >';
echo '<option value="">Nr Zadania | Typ Zadania | Nazwa Wioski</option>';
while($option = mysql_fetch_assoc($zadanie1)) {
echo '<option value="'.$option['id_zadania'].'">'.' '.$option['id_zadania'].' - '.$option['rodzaj_zadania'].' - '.$option['zad_cel_nazwa'].' '.'</option>';
}
echo '</select>';
and css rule
<style>
.cfp { display: none; }
.cfpa:checked + .cfp {
display: block;
}
</style>
and div outside form (inside FORM css display none - not working..
echo ' <div class="cfp">';
echo ' some other content';
if ($_POST['id_zadania'] == 7 ){ echo 'wybrales 7'; }
echo ' </div>';
I want to get selected variable, and display other part of the FORM
is it possible with PHP and CSS only?

If you don't want to press a button you can use the event onChange.
echo '<form>
<select name="inne_zad" class="cfpa" width="400" style="width: 400px" onChange="this.form.submit();" >';

Related

Make elements in a list clickable (PHP)

I'm currently developing a simple web page that enables the user to: upload an image and a corresponding caption to a DB, let the user view the images and delete them.
I have already accomplished the first two with the following code:
<?php
#include_once("connection.php");
$db = new mysqli("192.168.2.2", "root", "", "proyectoti");
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo "Información de servidor: ";
echo $db->host_info . "\n";
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); #$_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$sql = "INSERT INTO images (image, image_text) VALUES ('{$image}', '{$image_text}')";
// execute query
mysqli_query($db, $sql);
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
<!DOCTYPE html>
<html>
<head>
<title>Proyecto TI | Sube imágenes</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<h1>Proyecto TI | <a> Interfaz </a></h1>
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
#echo "<img src='images/".$row['image']."' >";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="image_text"
placeholder="Di algo de esta imagen ^^"></textarea>
</div>
<div>
<button type="submit" name="upload">Publicar</button>
</div>
</form>
</div>
</body>
</html>
It looks like this:
Now, the only part I'm missing is being able to delete an image (basically I only echo each image), how would you suggest for me to accomplish this, to make each item clickable and let's say, pop up a dialog or button to perform an action (delete from DB).
I really don't know much about PHP or CSS/HTML, any help would be much appreciated, Thank you!
Within this loop:
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
#echo "<img src='images/".$row['image']."' >";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
Personally I would add an element to click on - like an 'x' or whatever - with a unique data attribute:
https://www.abeautifulsite.net/working-with-html5-data-attributes
You have to add the unique id of the image obviously, so you can let SQL know which row to delete... Like this:
echo "<div class='delete-image' data-id='" . $row['id'] . "'>x</div>';
Then I would link this class to an AJAX call to make an asynchronous request to the server and delete the image without reloading the page. It's not very hard.
An easier solution would be to create a new form in the loop, so you create multiple forms per image, add a hidden field with the image id in the form and make a submit button with the valeu 'delete' or simply 'x'.
The same way you created the check:
if (isset($_POST['upload'])) { ... }
You can create something like this:
if (isset($_POST['delete-image'])) { ... }
You will be carrying the image id value like a normal form input. And you can do whatever you want with it.
I would HIGHLY suggest you to look into how to work with jquery and ajax calls though.
Opening a dialogue and ask the user before he deletes an item will require that you either go another page for deletion or use javascript for this.
In both cases, you should somehow set an identifier for your image in your html-code.
I would suggest you give every image an id
'<img ... id="'.$yourImageId.'">'
or a data-attribute
'<img ... data-identifier="'.$yourImageId.'" >'
with that identifier.
First variant:
...
echo '<a href="/path/to/delete/view/page.php?image=yourImageId">'
echo '<img ... id="'.$yourImageId.'"/>'
echo '</a>'
...
and on this delete-view-page, you just have a form that triggers your delete-code
<form action="/path/to/delete/view/page.php" method="POST">
<input type="hidden" name="id" value="<?php echo $yourImageId ?>">
</form>
<!-- after this, react with $_POST['id'] --> to the id sent to the server side and delete the image in your database -->
The other way is not server side rendered.
You should give your Elements some class like "my-clickable-image".After that, you have a script on your page, that looks something like the following
<script>
/* get your images with querySelectorAll, the . stands for class and after that your name */
var clickables = document.querySelectorAll(".my-clickable-image");
clickables.foreach(function(image){
// say that for each image, when clicked the generated function is called image.addEventListener('click',generateShowDialogueFunc(image.getAttr("id")));
});
// generate a function(!) that reacts to an image being clicked
function generateShowDialogueFunc(imageIdentifier){
// return a function that adds a Pop Up to the page
// the Pop Up has approximately the code of the first options second page
// except that now, it must create and remove elements in javascript
return function createPopUp(){
removePopUp();
var popup = document.createElement("div");
popup.setAttribute("id","deletePopUp");
var deleteForm = document.createElement("form");
deleteForm.setAttr("action","/path/to/file/that/deletes/given/query.php?id="+imageIdentifier);
var deleteContents = '<p> Do you want to delete this image? </p>'
+ '<button type="submit"> yes </button>'
+ '<button onclick="removePopUp()"> no </button>'
deleteForm.innerHTML = deleteContents;
document.body.appendChild()
}
}
// remove the Pop Up that can be used to delete an image from the page
function removePopUp(){
var existingPopUp = document.getElementById("deletePopUp");
if(existingPopUp) document.body.removeChild(existingPopUp);
}
</script>
<!-- just add some styling to make the popup show on top of the page -->
<style>
#deletePopUp{
width: 50vw;
height: 50vh;
position: absolute;
z-index: 1;
padding: 1em;
}
</style>
In this case, you just call the server to delete the image, not to show the delete form.
I would suggest the second one but stack overflow is not made for opinion based answers.
Regarding simple security:
It looks like your users could give titles or texts to images.
try what happens if a user gives a title like <bold>some title</title>
and guess what would happen if the title is <script>window.location.href="google.com"</script>
(XSS * hint hint *)
Regarding code structure:
If you want to do something like web development more often, think about separating your database accessing code, and your logic code from your php page template code, this is called 3 tier architecture and standard for bigger projects but i guess this is really just a first, short prototype or test.

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.

Unique Value For Each Button

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

Login Button similar to dropbox using images

I am currently trying to create a login button that is similar to that of dropbox. There is another thread available on how to do this, but I wish to do it differently. Note I tried to follow the code provided in that thread as close as I can, but it was a failed attempt.
Rather than having a link written in text, my button refers to a link through an image. Furthermore, when the button is pressed, I want another image to popup right below it.
Here is my code:
html/ jquery /php code:
echo '<div id = popup>';
echo '';
echo '<div id = "popupimage"> </div>';
echo '</div>';
echo '<script type="text/javascript src="jquery.js">';
echo '$("#popup").click(function(e){
$("#popupimage").css("visibility","visible");
e.stopPropagation();
});';
echo '</script>';
css code:
#logbutton{
top:50px;
left:850px;
position: absolute;
background-image: url(../images/buttons/loginbutton.png);
width:59px;
height:28px;
}
#popupimage{
top:63px;
left:887px;
position: absolute;
background-image: url(../images/popupimage.png);
visibility: hidden;
width:400px;
height:600px;
}
If possible I would also like to know if this can be done using html 5 and css only?
Thanks in advance
I have managed to do this. Here is the code:
echo '';
echo '<div id = "popup">';
echo '<div id = "popupimage"> </div>';
//HTML INSIDE POPUP
echo '</div>';
echo '<script type="text/javascript" src="jquery.js"></script>';
echo '<script>';
echo '$("#loginbutton").click(function(e){';
echo '$("#popup").css("visibility","visible");';
echo 'e.stopPropagation();';
echo '});';
echo '$("#popup").click(function(e){';
echo 'e.stopPropagation();';
echo '});';
echo '$("body").click(function(e){';
echo '$("#popup") . css("visibility", "hidden");';
echo '});';

DIV element not being pushed down by content inside it

I have a div which is not being pushed down by the content inside it. Instead the content just overlaps the div. I assume this is because there's a PHP while loop between the div tags? How do I fix this?
session_start();
if (!$_SESSION["user_name"])
{
header("Location: index.php");
}
include('header.php');
$id = $_GET['id'];
if(isset($id)) {
connect_to_db();
mysql_query("DELETE FROM content WHERE id='$id'");
$deleted = 'Content Successfully Deleted.<br>';
}
echo '<div id="content">';
echo '<h2>Delete Content</h2>';
if(isset($deleted)){
echo $deleted;
}
connect_to_db();
$query="SELECT id, date, title, image FROM content ORDER BY date DESC";
$result=mysql_query($query);
while($row = mysql_fetch_array($result)){
echo '<div id="delete" align="center">';
echo '<img src="'.$row['image'].'" style="border:1px solid black; width:100px;"><br>Delete';
echo '</div>';
}
echo '</div>';
Put overflow: hidden; CSS rule on the div which has the overlapping content in it.
try clearing the div inside the while loop, maybe something like
while($row = mysql_fetch_array($result)){
echo '<div id="delete" align="center">';
echo '<img src="'.$row['image'].'" style="border:1px solid black; width:100px;"><br>Delete';
echo '<div style="clear:both"></div></div>';
}
may help?
or declare the <a> element as a block element?
Using a PHP loop is not related to this issue, what matters is the HTML code that is served to your web browser.
Try adding a clear: both; style to the div in question:
<div id="delete" align="center" style="clear: both;">
You may also align using CSS instead of a HTML attribute:
<div id="delete" style="text-align: center; clear: both;">
UPDATE I see that your DIV elements are overleaping, not floating next to each other as I originally thought.
Check your CSS and see if you can find any position: absolute that applies to these DIV elements, and remove it. In addition, you should use class="delete" instead of id="delete", as multiple elements should not share the same id attribute.
For testing, you can try:
<div id="delete" style="text-align: center; position: block;">

Categories