Delete specific uploaded file from folder on server and display remaining files - javascript

going a bit crazy trying to get this to work... I have a photo upload page that lets you upload multiple photos and displays all the uploaded photos of a specific user below the upload form. I also place a delete button next to each photo however once you delete a photo it keeps displaying that image (although with a broken link as the photo is deleted from the server). I start by looping through a table that holds the file dir and name and then displays those photos. I have a submit button that calls the unlink() function.
$photoQuery= "SELECT * FROM photo_index WHERE User_ID='$UserID'";
$result = mysqli_query($dbcon, $photoQuery);
while ($photo_data = mysqli_fetch_array($result)){
echo "<form id=photo_Form action=listing_photos.php method=post> ";
echo "<input type=hidden name=photoDir value='$photo_data[Photo_Dir]' />";
echo "<input type=submit name=photoDel id=submit_but value=Delete />";
echo "</form>";
echo "<img src='$photo_data[Photo_Dir]' height=100px width=100px>";
}
Then here is the php that deletes the photo file and the row in the table that stored the photo info.
if (isset($_POST['photoDel'])){
$fh = fopen($_POST['photoDir'], 'a');
fclose($fh);
unlink($_POST['photoDir']);
$photoDel= "DELETE FROM photo_index WHERE Photo_Dir='$_POST[photoDir]'";
$result = mysqli_query($dbcon, $photoDel) or die(mysql_error());
echo "Photo Removed";
}
I had to open and close the file before using unlink because if I didnt I would always get a warning after the photo was deleted saying that unlink(images/somephoto.jpg) did not exist (because it had been removed from the server already)
Once the delete button is clicked it should refresh the page shouldn't it?? and when the page refreshes it should reload the query and only display the photos that are listed in the photo tabel?? For what ever reason it takes two refreshes to get that result. Any help would be very much appreciated, or any way to just do this better! Cheers.

First off, your code is vulnerable to SQL injection. You should look into that. Next, maybe you should use JS to find and remove the image from the document. So, have a <button> that runs a function which removes the image with that specific source from the document.
Here's a PHP snippet:
$photoQuery= "SELECT * FROM photo_index WHERE User_ID='$UserID'";
$result = mysqli_query($dbcon, $photoQuery);
while ($photo_data = mysqli_fetch_array($result)){
echo "<form id=photo_Form action=listing_photos.php method=post> ";
echo "<input type=hidden name=photoDir value=". $photo_data[Photo_Dir] . "/>";
echo "<input type=submit name=photoDel id=submit_but value=Delete />";
echo "</form>";
echo "<img src=" .$photo_data[Photo_Dir]. " id = 'picture' height=100px width=100px>";
echo "<script>
var d = getElementById('submit_but');
var b = getElementById('pic');
d.onclick = function(){
pic.parentNode.removeChild(b);
return true;
}
</script>";
}
See here for the JavaScript:
http://jsfiddle.net/BUXBq/

Related

How to make the div editable to textarea and upload/delete existing images

I have a website where user can upload images, name and description. I am saving it in mysql and fetching that information to show on my website. That's what my below code does, let the user enter those information (image and text) and show it on the website when they click submit button.
My question is how can I make the div (that shows images, name and desc) to editable when user clicks the edit button (so change that same div to textarea or something that is editable) and for images should have an cross mark near the image when clicked on edit button, so user can delete it and upload button to upload more images.
What I have done: I try to use javascript to get the value of div and use that to change it to textarea, but it says the value is undefined for the grid div.
So, how can I make my div editable as explained above, as what I have try so far is not complete, so is there any better way to make the div editable same way I explained above so user can edit text and upload or delete images?
My code:
<?php
require "database.php"; // connecting to database
session_start();
global $username;
$username = $_SESSION['userUsername'].$_SESSION['userId']; //fetching the username
$image = "userPos/$username"; //fetching image posted by specific user
function listFolderFiles($dir, $username){
<!-- The div my_class is getting the images from local storage
that was initially uploaded by user in the website
(and we stored it in the local storage) to display them on the website -->
echo '<div class="my_class">';
$ffs = scandir($dir);
unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);
// prevent empty ordered elements
if (count($ffs) < 1)
return;
foreach($ffs as $ff){
$s = "'<li>'.$ff";
$saving = "$dir/$ff";
$string = "$saving";
global $string_arr;
$string_arr = (explode("/",$string));
$sav;
$sav = '<li>'.$ff;
global $sa;
$sa = "$ff";
echo '<div class="imagess">';
if(is_file($saving)) {
echo '
<div class="images">
<img src="'.$saving.' " width="100" height="100" alt="Random image" class="img-responsive" />
</div>
' ;
}
echo `</div>`;
if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff, $username);
}
echo `</div>`;
require "database.php";
<!--Here we are fetching the name and description
that was entered by user on the website
and displaying them on the website now-->
$username = $_SESSION['userUsername'].$_SESSION['userId'];
$sql = "SELECT * FROM `_desc` WHERE `username` = '$username' AND `id` = '$string_arr[2]';";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
echo '</br>';
while($row = mysqli_fetch_assoc($result) ) {
//name and desc
echo '<div class="grid">' . '<h2>' . $row["_name"] . '</h2>' . '</div>';
echo '<div class="grid2">' . '<p>' . $row["_desc"] . '</p>' . '</div>';
}
<!--Here I am trying when user click on edit button it should
change that div to editable textarea so user can edit
and save it or delete the whole div-->
echo '<button onClick="editName()" class="btn btn-info">
Edit</button>';
echo '<a href="deleteUserInfo.php?edit= '.
$row["id"].'"class="btn btn-danger ">Delete</a>';
}
echo '</div>';
}
listFolderFiles($image, $username);
?>
<script>
function editName() {
console.log("calling");
var divName = $("grid").html();
console.log(divName); //value is undefined here
var editableName = $("<textarea />");
editableName.val(divName);
$("grid").replaceWith(editableName);
editableName.focus();
editableName.blur(saveName);
}
function saveName() {
var htmlName = $(editableName).html();
var viewableText = $("<div>");
viewableText.html(htmlName);
$(editableName).replaceWith(viewableText);
$(viewableText).click(editName);
}
</script>
</body>
</html>
It is quite simple, you should use contenteditable attribute available and set that value to true. This will make the div element editable.
Like this,
<div class="grid" contenteditable="true">I am editable!</div>
In your case, you should use a function to select the element and set the attribute to true. And for the div element on clicking the type='file' input tag, you can write function that will delete the file that is previously uploaded and upload the new file. I would recommend you to research before posting a question in the community as you might get negative impacts on such questions. Hope it helps! Happy coding!!
When the user clicks the edit button, set the contenteditable attribute to true on the target element and set the focus to that element.
function editName() {
$("grid").attr("contenteditable", true);
$("grid").focus();
$("grid").blur(saveName);
}

How to get input from user(text) when he presses a button(using a popup window) and save the data to a db?

I am building a site in which users have the ability to write post's and other users could comment on these posts.
By now I managed to create a div that contain the comment's that are posted, I have a "Like" button(not functional at this moment) and I have a "Comment" button that I want to trigger a small window that will open to recieve text from the user(the comment) and add it to my comment table(tblcomments).
The comment button has the same ID of the post it refers to(I built it that way when I echo'ed the page from php and everything sits in the same div). but I can't seem to find a way to pop-up that comment window to recieve the comment from the user and update my table with a comment for this specific post.
The section of the page that contains the comments is being refreshed every 5 seconds so adding a simple text field to the div is imposible cause it will get reset every 5 seconds.
that is how it looks on the page right now:
And that's the code that generate each and every post like this one on my main page while querying my DB:
<?php
include 'connectDB.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$hash = mysqli_escape_string($conn, $_SESSION['login_user']);
$resultfr = mysqli_query($conn, "SELECT distinct U.userName,concat(U.firstName,' ',U.lastname) as fullName FROM tblUser U inner join tblfriendswith FW on FW.userName1=U.userName or FW.userName2=U.userName where U.userName!='$hash'");
$uName="";
if($resultfr!= FALSE){
while($row2 = mysqli_fetch_array($resultfr)){
$uName= $uName.$row2['userName']." ";
}
}
$result = mysqli_query($conn, "SELECT U.userName,concat(U.firstName,' ',U.lastname) as fullName,MONTHNAME(P.postDate) as dateM, DAY(P.postDate) as dateD, YEAR(P.postDate) as dateY, P.postID, P.content FROM tblUser U inner join tblPost P on P.userName=U.userName where U.userName in ('$uName','$hash') order by P.postDate desc");
if($result!= FALSE){
echo "<div class='forPosts'>";
while($row = mysqli_fetch_array($result)){
$fullName = $row['fullName'];
$day=$row['dateD'];
$month=$row['dateM'];
$year=$row['dateY'];
$content = $row['content'];
$postID=$row['postID'];
echo "<div class=\"divStyle2\"><span class=\"myText2\">Posted by " .$fullName." - ".$day." ".$month." ".$year."</span><br><div class=\"divStyle\">".$content."</div>";
echo "<br><button class=\"myButton\"> <span class=\"glyphicon glyphicon-heart pull-left\"></span>&nbspLike</button>&nbsp &nbsp<button class=\"myButton\"><span class=\"glyphicon glyphicon-comment pull-left\"></span>&nbsp Comment</button>&nbsp &nbsp<button class=\"myButton\" name=\"clickB\" id=\"".$postID."\"><span class=\"glyphicon glyphicon-triangle-bottom pull-left\"></span>&nbsp Show/hide comments</button></div>";
//echo "<p class=\"alignW\"><input class=\" col-sm-5\" type=\"text\" name=\"comment\" id=\"".$postID."\" placeholder=\"Write a comment\"></div>";
$result2 = mysqli_query($conn, "SELECT C.postID, C.commentID, C.userName, C.content,concat(U.firstName,' ',U.lastname) as fullN,MONTHNAME(C.commentDate) as dateM, DAY(C.commentDate) as dateD, YEAR(C.commentDate) as dateY FROM tblUser U inner join tblComment c on U.userName=C.userName where C.postID=$postID order by C.commentDate desc");
if($result2!= FALSE){
echo"<div class='forComments'>";
while($row2 = mysqli_fetch_array($result2)){
$fullN = $row2['fullN'];
$day2=$row2['dateD'];
$month2=$row['dateM'];
$year2=$row2['dateY'];
$content2 = $row2['content'];
echo "<div class=\"divStyle2\" id=\"".$postID."\"><span class=\"glyphicon glyphicon-comment\" ></span><span class=\"myText3\">&nbsp" .$fullN. " : ".$content2."</span></div>";
}
}echo"</div>";
}
echo "</div>";
}
echo" <script>
$(document).ready(function(){";
echo" $(\"button[name=clickB]\").click(function() {
link = $(this).attr('id');
$('div[id=\"'+link+'\"]').toggle();
$(\"span\", this).toggleClass(\"glyphicon glyphicon-triangle-bottom glyphicon glyphicon-triangle-top\");
});";
echo"}); </script>";
?>
I use mysqli and xampp.
I would be grateful if someone could help me to achieve my task.
Thank you!
Tom

How to display the body of the mail in another page if clicked on the subject

So I am creating an inbox in PHP and It displays Mail Id and Subject.
If you click that division(containing mail id and subject), it opens up a new page, read. PHP where the body and attachments are displayed.
I am facing some problem in getting to know which division is being clicked and how to display the mail of that particular person.
My concerned code is:
<?php
$conn = connect(); //Connects to the database
$sql = "select senderId, subject, body, attachment from mail where receiverId = '".$_SESSION["Email"]."' ";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "<div class='mail' onclick='location.href=`read.php`;'>";
echo $row["senderId"] . " - " . $row["subject"];
echo "</div>";
echo "<hr />";
}
$conn->close();
?>
I have an idea of storing the variables using SESSION as:
if (isset($_GET['div'])) {
$_SESSION["body"] = $row["body"];
$_SESSION["attachment"] = $row["attachment"];
}
But where do I place the latter part of the code and suggest me if I can make an modifications please.
You can echo out the id during the while loop iteration.
echo "<div class='mail' onclick='location.href=`read.php?id=". $row['id'] ."`;'>";
And inside the read.php file, you can then grab that value by using $_GET['id'].

Is it possible to combine javascript/jquery and mysql/php

I have a odd question i cannot find the answer to, which probably means it is impossible. The reason i ask is i am creating a food delivery website. In the admin panel of my website administers are able to input restaurant details and menus. Part of the details is how much a customer must spend before they can checkout for delivery. so i want to be able to deactivate the checkout button, but when they met the minimum order fee the button activates.
This is my first time attempting anything like this, i have looked all over and i can only find posts or tutorials on how to deactivate then activate a button when a certain event takes place using javascript or jQuery and i know i would have to get the minimum order fee from the DB.
The only logical answer is to combine them.
I am trying to achieve something similar to this...
Shopping
I followed a tutorial to do this, it is a mini fixed shopping cart, which is on the same page as the shopping cart. It redirects to shopping_cart.php from product_page.php. Most aspects on product_page.php is dynamically made.
mysqli_stmt_execute($runn_query);
while ($get_row = mysqli_fetch_array($runn_query)) {
echo "<div id='prods_ere'>";
$item_sub = $get_row['Product_Price'] * $value;
echo $value . ' x ' .$get_row['Product_Name']. ' # £' . $get_row['Product_Price'] . '<a id="minus" class="buttons" href="Shopping_cart.php?remove=' . $Product_Id . '">-</a> <a id="plus" class="buttons" href="Shopping_cart.php?add_item=' . $Product_Id . '"> + </a> <a id="del" class="buttons" href="Shopping_cart.php?delete=' . $Product_Id . '">✖</a> </br><p id="sub">£' . $item_sub . '</p>';
echo "<br>";
echo "<br>";
echo "<hr id='shopp_dashed'>";
echo "</div>";
}
}
//creating subtotal
$sub_total += $item_sub;
$num_items += $value;
$total += $sub_total;
}
}
//subtotal and empty cart message
if ($sub_total == 0) {
echo "Ouch.. its empty in here";
} else {
echo "<div id='grey'>";
echo"Subtotal (excl delivery)";
echo "<br/>";
echo "<div id='sub_t'>";
echo '£' . number_format($sub_total, 2);
echo "</div>";
echo "<br/>";
echo"Items";
echo "<br/>";
echo "$num_items";
echo "<br/>";
echo "</div>";
echo "<div id='total'>";
echo"Total: ";
echo "$total";
echo "</div>";
}
Products page
<div id="prods_here">
<!-- PLACE PRODUCTS HERE-->
<?php cart(); ?>
</div>
Well, I'm not sure how you're keeping track of the customer's order but let's say you're keep track of it in a counter, say, totalOrderAmt. As they are making changes to the order, keep this updated and add a condition to the page, that when the totalOrderAmt >= checkOutAmt, enable the checkOut button.
I can add more details if you post some code, may be.
If you're using PHP you could load a JavaScript object on each restaurant page that basically makes a minimum_order_price variable available on the DOM for the JavaScript to handle the rest:
<html>
<head>
...
</head>
<body>
<h1>Restaurant X</h1>
<p>Minimum order: <span id="_restaurantMinimumOrder"></span></p>
<input id="submit" type="submit" class="disabled" value="Checkout" disabled>
<script type="text/javascript">
<?php
echo "window.RestaurantDetails = {}";
echo "window.RestaurantDetails.minimum = $RestaurantMinimumOrder";
?>
</script>
</body>
</html>
In this instance, $RestaurantMinimumOrder is something you configure and setup on PHP (I am not sure what you're setup is so I went with a variable name). From there, when the page is parsed from the server, the PHP will echo out that JavaScript. Once the page loads, window.RestaurantDetails will be available for the rest of your JavaScript to use. I've also included an example implementation:
<script type="text/javascript">
// set price on the DOM
var priceEl = document.getElementById('_restaurantMinimumOrder');
priceEl.textContent = window.RestaurantDetails.minimum;
// ensure submit button is disabled initially
var submitEl = document.getElementById('submit');
submitEl.disabled = true;
</script>
From here, if you're using jQuery you can easily adjust the state of the submit button based on whatever logic flow you have setup. Let me know if you have more questions. Best of luck! Cheers ~

Passing a var in the same php page without refresh

I have a problem with my website. I have a list of products that i get from database. These products have Image and Name camps.
Now i want that, when i click to someone of this products, into my webpage appears a new box where there is the description of the product, the price etc..
This is the code for the products list
<?php
include 'php/dbmanager.php';
$result = DBManager::getInstance()->getProducts();
if($result->num_rows > 0){
$i = 0;
while($row = $result->fetch_assoc()){
echo "<div class=\"wrap effect8 open\" onclick>";
echo "<h1>".$row['product_name']."</h1>";
echo "<div class=\"left\">";
echo "<img src=".$row['product_image']." width=150 height=150 >";
echo "</div>";
echo "<div class=\"right\">";
echo $row['product_description'];
echo "<div class=\"prodSelection\">";
echo '<a href="catalogo.php?prodID=';
echo $row[product_id];
echo '"';
echo 'class="button">Acquista</a>';
echo '<label>';
echo '<select class="selectBoxCat">';
echo '<option selected> 1 </option>';
echo '<option>2</option>';
echo '<option>3</option>';
echo '</select>';
echo '</label>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
How can i get the ProductID ($row[product_id]) from a single product that i click and use it for a new query for select the database's rows of this single product (and use this query for make another php like that)?
I dont want to refresh the page.
Could i use the pushstate method (HTML5)?
If you want to get additional data when the user clicks, you will need to make an ajax request to update your DOM without refreshing the page.
On the PHP side, you'll want to create a script that returns a json-encoded value.
On the JS side, you'll want to create a click event listener. Inside the listener, you'll want to make an ajax request to your PHP script.
When your data is successfully returned from your ajax call, you'll want to manipulate your DOM to display your product's details.
Example of a click listener:
$("#button").on("click", function(){
// make your ajax request here
});
Example of an ajax call:
$.ajax({
method: "POST",
url: "scriptThatReturnsProductDetails.php",
data:
{
productID: $("#myProduct").attr('id')
}
})
.done(function( msg ) {
// Do some DOM manipulation
});

Categories

Resources