After a picture is uploaded I want to let the user have the option to delete it by clicking on the 'x' on the image. I tried some jquery codes that I searched online but nothing had the result I want. Is there a way to remove the image from the database only when the submit button is clicked rather than redirecting to a delete page and then having to go back to delete another image?
if($res18 && mysql_num_rows($res18) > 0){
while($row18 = mysql_fetch_assoc($res18)){
if (file_exists($row18['images']) === true){ ?>
<?php
//mysql_query("DELETE FROM `images` WHERE `images`='".$row18['images']."' AND `ad_id` = '".$id."'");
echo '<img src="'.$row18['id'].'" class="pictures">';
}
}
}
insert quesry:
mysql_query("INSERT INTO `images` ($fields) VALUES ($data)");
I assume the logic would be somewhat like this: Once the 'x' link is clicked, run a function that runs the delete query.
Any help is appreciated!
UPDATE:
$res18 = mysql_query("SELECT * FROM `images` WHERE `ad_id` = '" . $id . "'");
if($res18 && mysql_num_rows($res18) > 0){
while($row18 = mysql_fetch_assoc($res18)){
$picture = $row18['images'];
$pic_id = $row18['id'];
if (file_exists($picture) === true){ ?>
<img src="<?php echo $picture ?>" id="img-<?php echo $picture ?>" class="pictures">
<?php
}
}
}
<script type="text/javascript">
$(document).ready(function(){
// set onclick for all 'a' elements having the 'addition_image_close' class
$('a.addition_images_close').click(function() {
var $pic_id = $(this).prop('data-id');
var $picture = $(this).prop('data-id');
// post to delete.php, sending id=$picture as data and setting success handler
$.post('delete.php', {id: $picture}, function() {
// remove elements from page
$('#img-' + $picture).remove();
$('#a-' + $pic_id).remove();
});
});
});
</script>
and the delete.php has the following:
$id = $_GET['id'];
mysql_query("DELETE FROM `images` WHERE `ad_id` = '".$id."'");
a list.php could be something like this:
<?php
// ...
// render list
if($res18 && mysql_num_rows($res18) > 0) {
while($row18 = mysql_fetch_assoc($res18)) {
if (file_exists($row18['images']) === true){ ?>
<a href="javascript:return(0);"
class="addition_images_close"
data-id=<?php echo $row18['id'] ?>
id="a-<?php echo $row18['id'] ?>"
>X</a>
<img src="<?php echo $row18['id'] ?>"
id="img-<?php echo $row18['id'] ?>"
class="pictures">
}
}
}
?>
<!-- add actions on the links rendered above -->
<script type="text/javascript">
// do this when page is loaded
$(document).ready(function(){
// set onclick for all 'a' elements ahving the 'addition_image_close' class
$('a.addition_image_close').click(function() {
var $id = $(this).prop('data-id');
// post to delete.php, sending id=$id as data and setting success handler
$.post('delete.php', {id: $id}, function() {
// remove elements from page
$('#img-' + $id).remove();
$('#a-' + $id).remove();
});
});
});
with a delete.php receiving an id parameter and performing the delete query
Related
i have a row in the table 'files' where 'id' is a unique identifier column, and equals $imgId. imgId=$row['id'];
<script type="text/javascript">
$( "#<?php echo $imgId ?>" ).click(function() {
<?php
$sql = "DELETE FROM files WHERE id=$imgId";
if ($con->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $con->error;
}
$conn->close();
?>
});
</script>
I am displaying multiple embeds where the html id is equal to the unique identifier sql column id for that image.
<embed id="<?php echo $imgId; ?>"class="delete-row" src="<?php echo $filePath; ?>" type="<?php echo $fileMime; ?>"/>
I just want it so when you click on a spcific image it deletes it from the database and removed the image file from the /uploads folder. Any help would be awesome.
The way that you are performing this is not advisable. You cannot use mysql pdo objects inside jquery click function. I suggest that you use the below approach. Please see that this is just a baseline. Please feel free to change the code as per your requirement.
In the html file or where you are using the script tag, use the below syntax:
<script type="text/javascript">
jQuery(".delete-row").click(function(){
var imageId = jQuery(this).attr('id');
var filePath = jQuery(this).attr('src');
jQuery.ajax({
type: "POST",
url: "[DOMAIN]/deleteImage.php",
data: {imageId: imageId, path: filePath},
success: function(res) {
if (res === "deleted") {
jQuery(this).remove();
}
}
});
});
</script>
In the deleteImage.php file:
<?php
require 'conn.php';
if (!empty($_POST['imageId'])) {
$sql = "DELETE FROM files WHERE id=$imgId";
if ($con->query($sql) === TRUE && unlink($_POST['path'])) {
return "deleted";
} else {
return false;
}
}
$conn->close();
return false;
?>
Hope this helps.
I am trying to post a variable clicked by an user to a PHP script in order to run a query which will further extract information from the database. I am able to get the value that has been clicked by an user without any issue. However I believe it is not getting processed within the query hence why when I run it in Firebug it shows an empty response and HTML.
I think I need some changes with my test.php script or may be ajax part of index.php
Index.php
<?php
$test = $_GET['product'];
$q = "SELECT * FROM prdct_categories WHERE product = '$test' ";
$r = mysqli_query($dbc, $q);
$path_info = get_path();
$test1 = $path_info['call_parts'][1];
while ($list = mysqli_fetch_assoc($r)) { ?>
<li class="nav" <?php if ($test1 == $list['slugs']) { echo'id="actives"'; } ?>>
<a href="<?php echo $test;?>/<?php echo $list['slugs'];?> ">
<?php echo $list['subgroup'] . "(" . $list['contains'] . ")" . '<br/>'; ?>
</a>
</li>
<?php } ?>
</div>
<div class="col-md-4" id="testing"></div>
<script>
$(document).ready(function() {
$(".nav > a").click(function(e){
e.preventDefault();
$.post("test.php", { value:$(this).text() }, function(data) {
$("#testing").html(data);
});
});
//var classprod = $(this).text();
//$("#testing").text(classprod);
});
</script>
test.php
<?php
require('../config/connection.php');
if (isset($_POST['value'])) {
$value = $_POST['value'];
$query = "SELECT * FROM prdct_categories WHERE class = '$value'";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_assoc($result)) {
$prdct = print_r ($row['product']);
echo $prdct;
}
}
?>
remove "<br>" from
<a href="<?php echo $test;?>/<?php echo $list['slugs'];?> ">
<?php echo $list['subgroup']."(".$list['contains'].")".'<br/>';?></a>
and try
or try in js as
$.post("test.php", {value:(($(this).text()).trim())},
Change this:
$prdct = print_r ($row['product']);
To this:
$prdct = $row['product'];
Also change this:
$(".nav > a").click(function(e){
e.preventDefault();
$.post("test.php", {value:$(this).text()},
function(data) {$("#testing").html(data);});
});
To this:
$(".nav > a").click(function(e){
$.ajax({
type: "POST",
url: "test.php",
data: {value: $(this).text()},
success: function( msg ){$("#testing").html(msg);}
})
});
I have a like/unlike post on my website, and when I click the like button I would like the value of check2 to show beside like without me having to refresh the page to see it. Currently I'll click like and it inserts the data but only shows on a page refresh. I'm hopeless with this kind of stuff.
Here is the code in the order it executes.
Thanks for any help.
POST LIKE
echo "<div class='stream_option'><a id='likecontext_".$streamitem_data['streamitem_id']."' style='cursor:pointer;' onClick=\"likestatus(".$streamitem_data['streamitem_id'].",this.id);\">";
if($checklikes>0){
echo "Unlike";
}else{
echo "Like";
}
echo "</a> ";
$check2 = user_core::print_like_count($streamitem_data['streamitem_id']);
if($check2>0){
echo "(".$check2.")";
}
Ajax Function
function likestatus(postid,contextid){
var obj = document.getElementById(contextid);
if(obj.innerHTML=="Like"){
obj.innerHTML="Unlike";
}else{
obj.innerHTML="Like";
}
$.post("../include/like_do.php", { streamitem_id: postid} );
}
LIKE_DO
$check = user_core::check_liked($_SESSION['id'],$_POST['streamitem_id'],1);
user_core::do_like($_SESSION['id'],$_POST['streamitem_id'],1);
if($check==0){
?>
<?php
}else{
?>
<?php
}
}
else{
echo "<script>alert('Error liking post');</script>";
}
?>
USER_CORE
function check_liked($id,$streamid,$value){
$check = "SELECT feedback_id FROM streamdata_feedback WHERE feedback_streamid=$streamid AND feedback_userid=$id AND feedback_rating=$value";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
return $check2;
}
function print_like_count($streamid){
$check = "SELECT feedback_id FROM streamdata_feedback WHERE feedback_streamid=$streamid AND feedback_rating=1";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
if($check2>0){
echo "(".$check2.")";
}
}
What you're looking for is an AJAX submission using DHTML to change the value of the likes.
<script language="javascript">
$(".likeButton").click(function() {
$.post("likeProcessor.php", {
id: $(this).attr('id')
}, function(data) {
$("#likeIndicator" + $(this).attr('id')).html(data);
});
</script>
Then your likeProcessor script will simply return the number of likes for that item.
NOTE: This is pseudo-code to give you an idea of what needs to happen. For further info on jQuery and Ajax, RTM at http://www.w3schools.com/jquery/default.asp and http://www.w3schools.com/ajax/default.asp respectively.
I have this function that is suppose to change the html of a span. It works the first time but anyclick after that it doesn't change anything. I know the query is working because the database is updating. Here's the code.
$('#availabilityicon').click(function() {
$.ajax({
type: "GET",
url: "includes/changeavailability.php",
success: function(msg) {
if(msg === "available") {
var vailspan = $('span#avail').html('<a id="availabilityicon" href="#"><img align="center" width="16px" height="16px" src="images/available.png" /></a>');
}
else if(msg === "unavailable") {
var availspan = $('span#avail').html('<a id="availabilityicon" href="#"><img align="center" width="16px" height="16px" src="images/unavailable.png" /></a>');
}
}
});
});
here is the php code
<?php
session_start();
$user = $_SESSION['username'];
include("dbcon.php");
$result = mysql_query("SELECT availability FROM user WHERE username='$user' ORDER BY id DESC") or die(mysql_error());
$row = mysql_fetch_assoc($result);
$availability = $row['availability'];
if($availability == 'yes') {
$query = mysql_query("UPDATE user SET availability='no' WHERE username='$user'") or die(mysql_error());
echo "unavailable";
}
elseif($availability == 'no' or $availability == "") {
$query = mysql_query("UPDATE user SET availability='yes' WHERE username='$user'") or die(mysql_error());
echo "available";
}
mysql_close($con);
?>
There's a spelling mistake in your javascript, you've put vailspan where you probably meant to put availspan after the if(msg === "available") { line.
If it's not that, try changing the click event to a live one:
$('#availabilityicon').live('click', function() {
just in case your javascript is overwriting that the #availabilityicon icon element and failing to re-attach the event to the new one
The "availabiltyicon" you click is being replaced with another with the same name. You can try using .live() or you can read up on event delegation.
My PHP script generates a table with rows which can optionally be edited or deleted. There is also a possibility to create a new Row. The PHP is activated through jQuery Events.
Now all works well, I can edit delete and create an Item. After each action which makes use of the PHP script the HTML table gets updated.
But when I try after an Event to do an action again the HTML Table doesn't get updated though in the background the PHP script makes an entry into the database.
Does someone of you know why my HTML Table doesn't update itself when I trigger a second event?
Here is the Script:
PHP
<?php
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD)
or die ("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME,$dbh)
or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if($action == "new")
{
mysql_query("INSERT INTO `place` (`id`, `name`) VALUES (NULL, '$name')");
}
elseif($action == "edit")
{
mysql_query("UPDATE `place` SET `name` = '$name' WHERE `id` = '$id'");
}
elseif($action == "delete")
{
mysql_query("DELETE FROM place WHERE id = '$id'");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=".$row["id"]." class=inputfield_td><input class=inputfield_place type=text value=".$row["name"]." /></td><td class=place_name>".$row["name"]."</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
?>
JS
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function (html){
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display","none").prevAll(".place_name").css("display","none").prevAll(".inputfield_td").css("display","block").nextAll(".cancel").css("display","block").nextAll(".save").css("display","block").prevAll(".inputfield_td").css("display","block");
});
$(".cancel").live("click", function() {
myvariable5 = $(this).prevAll(".place_name").html();
$(this).css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none").nextAll(".save").css("display","none").siblings().find("input[type=text]").val(myvariable5);
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display","none").prevAll(".cancel").css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none");
$.post("place/place_list.php", {action: "edit", name: ""+myvariable1+"", id: ""+myvariable2+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
$.post("place/place_list.php", {action: "delete", id: ""+myvariable3+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {action: "new", name: ""+myvariable4+""}, function (html){$("#place_container").replaceWith(html);});
});
});
I think I know. You do replaceWith instead of append, so your DIV with ID #place_container disappears after the first operation (you are left with only a table in your page), and of course jQuery does not find it and is unable to refresh it with new content from the second operation.
Just use append or, better yet, html methods.
Shouldnt you replace the complete table ?
$("#place_container").html(html);