I'm trying to delete image box with ajax, my class="box" doesn't disappear when i click delete but my image has been deleted from database and unlink from folder, can anyone see if somethings wrong with my code, thanks in advance!
My code :
<ul>
<?php while ($result = mysql_fetch_array($sql)) { ?>
<li class="box">
<div class="image-box">
<div class="items-image" style="background-image: url(upload/<?php echo $result['img_1']; ?>);"></div>
<p class="error" style="display: none;">Can't delete</p>
<div class="items-footer">
<a class="delete" id="<?php echo $result['img_id']; ?>"><i class="fa fa-trash fa-lg"></i></a>
</div>
</div>
</li>
<?php } ?>
</ul>
$(document).ready(function(){
$(".delete").on('click', function(evt){
var del_id = $(this).attr('id');
var prop_id = "<?php echo $ID; ?>";
$.ajax({
type:'POST',
url:'image_delete.php',
data: ({delete_id : del_id, product_id: prop_id}),
success: function(data) {
if(data == '0') {
$(".error").show();
} else if(data == '1') {
$(this).parents(".box").animate({ backgroundColor: "#003" }, "slow").animate({ opacity: "hide" }, "slow");
}
}
});
});
});
image_upload.php
<?php
include 'connect.php';
$path = "upload/";
if(isset($_POST['delete_id'])){
$delete_id = $_POST['delete_id'];
$product_id = $_POST['product_id'];
$check = mysql_query("SELECT COUNT(img_id) as cnt FROM fm_product_image WHERE p_id_img = '$product_id'") or die(mysql_error());
$getcheck = mysql_fetch_array($check);
if($getcheck['cnt'] == '1') {
echo '0';
} else {
$sql = mysql_query("SELECT img_1 FROM fm_product_image WHERE img_id = '$delete_id'") or die(mysql_error());
$result = mysql_fetch_array($sql);
$delete = $result['img_1'];
$unlink = $path.$delete;
if (unlink($unlink)) {
mysql_query("DELETE fm_product_image FROM fm_product_image WHERE img_id = '$delete_id'") or die(mysql_error());
echo '1';
} else {
echo '0';
}
}
}
?>
Use remove:
$(document).ready(function(){
$(".delete").on('click', function(evt){
var del_id = $(this).attr('id');
var prop_id = "<?php echo $ID; ?>";
var box = $(this).closest(".box");
$.ajax({
type:'POST',
url:'image_delete.php',
data: ({delete_id : del_id, product_id: prop_id}),
success: function(data) {
if(data == '0') {
$(".error").show();
} else if(data == '1') {
box.animate({ backgroundColor: "#003" }, "slow").animate({ opacity: 0 }, "slow");
box.remove();
}
}
});
});
});
note: $(this) refers to the ajax object and opacity is a value from 1 to 0
Related
I have below code to get more results on page scroll.
It works fine on localhost and on server laptop/desktop.
It does not work on mobile and does not load more results on scroll.
I cannot figure it out why this is happening or what is causing this not to work on mobile.
<?php
$getItemLID = $dba->prepare('SELECT MAX(id) as id FROM items
where status = ? AND ename like ?');
$getItemLID->bind_param('ss', $status,$param);
$getItemLID->execute();
$resultLID = $getItemLID->get_result();
$rowLID = $resultLID->fetch_assoc();
$thelastid = $rowLID['id'];
$status = 1;
$getscategory = $dba->prepare('SELECT * FROM mytable
where status = ?
order by id asc');
$getscategory->bind_param('s', $status);
$getscategory->execute();
$resultGSC = $getscategory->get_result();
while ($rowGSC = $resultGSC->fetch_assoc()) {
$scid = $rowGSC['id'];
$scename = $rowGSC['ename'];
?>
<div class="message_box" data-id="<?php echo $scid; ?>" style="padding-right: 5px;">
<div class="portfolio-item-wrap" style="border-radius: 3%;">
<span class="portfolio-description">
<h3><?php echo $scename; ?></h3>
</span>
</div>
</div>
<?php } ?>
<div id="msg_loaderw" style="display: none;">
<div class="card">
<div class="card-body">
<div class="d-flex align-items-center">
<strong>Loading...</strong>
<div class="spinner-border ml-auto" role="status" aria-hidden="true">
</div>
</div>
</div>
</div>
</div>
<div id="msg_loader">
</div>
<script>
$(document).ready(function () {
$(window).scroll(function () {
var thislastid = "<?php echo $thelastid; ?>";
if($(window).scrollTop() == ($(document).height() - $(window).height())) {
$("#msg_loaderw").show();
var msg_id = $(".message_box:last").data("id");
$.ajax({
type: "POST",
url: "inc/items/search_items_get.php",
data: {msg_id: msg_id},
cache: false,
success: function (data) {
//Insert data after the message_box
$(".message_boxx").append(data);
if (msg_id == thislastid) {
$("#msg_loaderw").hide();
$("#msg_loader").html('<hr><div class="card"><div class="card-body"><div class="align-items-center"><strong><center>That is all what we have for now.</center></strong></div></div></div>');
}
}
});
}
});
});
</script>
Below is : inc/items/search_items_get.php
<?php
include ('../default/db.php');
if (isset($_POST['msg_id']) && isset($_POST['msg_id']) !== NULL) {
$msg_id = $_POST['msg_id'];
$status = 1;
$limit = 12;
$getItem = $dba->prepare('SELECT * FROM mytable
where id > ? AND status = ?
order by id asc');
$getItem->bind_param('ss', $msg_id,$status);
$getItem->execute();
$resultItem = $getItem->get_result();
while ($rowItem = $resultItem->fetch_assoc()) {
$itemID = $rowItem['id'];
$itemName = $rowItem['ename'];
?>
<div class="message_box" data-id="<?php echo $itemID; ?>" style="padding-right: 5px;">
<div class="portfolio-item-wrap" style="border-radius: 3%;">
<span class="portfolio-description">
<h5><?php echo $itemName; ?></h5>
</span>
</div>
</div>
<?php
}
} else {
echo "Message ID is empty";
}
?>*emphasized text*
It seems it's a script issue just try changing the code a bit , hopefully it will work:
<script>
$(document).ready(function () {
$(window).scroll(function () {
var scrollHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
$("#msg_loaderw").show();
var msg_id = $(".message_box:last").data("id");
$.ajax({
type: "POST",
url: "inc/items/search_items_get.php",
data: {msg_id: msg_id},
cache: false,
success: function (data) {
//Insert data after the message_box
$(".message_boxx").append(data);
if (msg_id == thislastid) {
$("#msg_loaderw").hide();
$("#msg_loader").html('<hr><div class="card"><div class="card-body"><div class="align-items-center"><strong><center>That is all what we have for now.</center></strong></div></div></div>');
}
}
});
}
});
});
</script>
Please note, I have gone through the below StackOverflow question which is exactly what i need but unfortunately, it isn't posting
Question similar to
My Code -
Test.php
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
<ul id="sortable">
<li id="item-1">Item 1</li>
<li id="item-2">Item 2</li>
</ul>
Span 1: <span id="span"></span>
Span2: <span id="span2"></span>
<script>
$(document).ready(function () {
$('ul').sortable({
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
$('#span2').text(data);
$.ajax({
data: data,
type: 'POST',
url: 'test2.php',
success: function(data){
$("#span").text(data);
}
});
}
});
});
</script>
Test2.php
<?php
include('../db.php');
$date = $_POST["data"];
$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE table SET something = '$something'
WHERE id = '$id'";
if(mysqli_query($conn, $sql)){
echo $date;
}
$conn->close();
?>
Can anyone help me out why the data is not posting to test2.php page
and
how can i sort the table using the data posted to test2.php
Thanks in advance.
For those who came across the same problem here's the solution :
Test.php
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
<ul id="sortable">
<?php
$q = ' SELECT * FROM temp';
$result = mysqli_query($conn, $q);
if ($result->num_rows > 0) {
while( $items = $result->fetch_assoc() ){
?>
<li id='sort_<?php echo $items['id'] ?>'>
<ul style="display:inline-block;"><?php echo $items['name'] ?></ul>
<ul style="display:inline-block;"><?php echo $items['name'] ?></ul>
</li>
<?php
}
}
?>
</ul>
<script>
$(document).ready(function () {
$('#sortable').sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var post = $(this).sortable('serialize');
$.ajax({
type: 'POST',
url: 'test2.php',
data: post,
dataType: 'json',
cache: false,
success: function(output) {
console.log('success -> ' + output);
},
error: function(output) {
console.log('fail -> ' + output);
}
});
}
});
});
$('#sortable').disableSelection();
</script>
Test2.php
<?php
$isNum = false;
foreach( $_POST['sort'] as $key => $value ) {
if ( ctype_digit($value) ) {
$isNum = true;
} else {
$isNum = false;
}
}
if( isset($_POST) && $isNum == true ){
$orderArr = $_POST['sort'];
$order = 0;
if ($stmt = $conn->prepare(" UPDATE temp SET o_id = ? WHERE id=? ")) {
foreach ( $orderArr as $item) {
$stmt->bind_param("ii", $order, $item);
$stmt->execute();
$order++;
}
$stmt->close();
}
echo json_encode( $orderArr );
$conn->close();
}
?>
Hope it helps the one in need.
I'm trying to load posts of users from my database to the website but the ajax part isn't loading for some reason. It was working on localhost but not working on the live server. Is there some problem in the ajax code or the code written in the index page?
Here in the index page the posts_area div part isn't loading
index.php
<?php
include("includes/header.php");
if(isset($_POST['post'])){
$post = new Post($con, $userLoggedIn);
$post->submitPost($_POST['post_text'], 'none');
}
?>
<div class="main_column column">
<form class="post_form" action="index.php" method="POST">
<textarea name="post_text" id="post_text" placeholder="Got something to say?"></textarea>
<input type="submit" name="post" id="post_button" value="Post">
<hr>
</form>
<div class="posts_area"></div>
<img id="loading" src="assets/images/icons/loading.gif">
</div>
<div class="user_details column">
<h4>Popular</h4>
<div class="trends">
<?php
$query = mysqli_query($con, "SELECT * FROM trends ORDER BY hits DESC LIMIT 9");
foreach ($query as $row) {
$word = $row['title'];
$word_dot = strlen($word) >= 14 ? "..." : "";
$trimmed_word = str_split($word, 14);
$trimmed_word = $trimmed_word[0];
echo "<div style'padding: 1px'>";
echo $trimmed_word . $word_dot;
echo "<br></div><br>";
}
?>
</div>
</div>
<script>
var userLoggedIn = '<?php echo $userLoggedIn; ?>';
$(document).ready(function() {
$('#loading').show();
//Original ajax request for loading first posts
$.ajax({
url: "https://bestconnect.000webhostapp.com/includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(data) {
$('#loading').hide();
$('.posts_area').html(data);
}
});
$(window).scroll(function() {
var height = $('.posts_area').height(); //Div containing posts
var scroll_top = $(this).scrollTop();
var page = $('.posts_area').find('.nextPage').val();
var noMorePosts = $('.posts_area').find('.noMorePosts').val();
if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') {
$('#loading').show();
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=" + page + "&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(response) {
$('.posts_area').find('.nextPage').remove(); //Removes current .nextpage
$('.posts_area').find('.noMorePosts').remove(); //Removes current .nextpage
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //End if
return false;
}); //End (window).scroll(function())
});
</script>
</div>
ajax_load_posts.php
<?php
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit = 10; //Number of posts to be loaded per call
if (isset($_GET['posts'])) {
$posts = new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST, $limit);
}
?>
<?php
header("Access-Control-Allow-Origin: *");
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit = 10; //Number of posts to be loaded per call
if (isset($_GET['userLoggedIn']))
{
$posts = new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST, $limit);
}
?>
I am receiving a 500 internal server error when making an ajax call.
$(document).ready(function(){
$("#txtSearch").change(function(){
var search = $("#txtSearch").val();
var str = 'search=' + search;
$.ajax({
type: "POST",
url: "searchProcess.php",
data: str,
dataType: "json",
success: function(data) {
if (data["type"] == "1") {
alert('Please Enter Value To Search');
}else if (data['type'] == "2") {
alert('No Such of This Event In Database');
}else if (data['type'] == "3") {
$('#gallery').hide().html(data['data']).fadeIn('5s');
}
}
});
});
});
searchProcess.php
if (!isset($_POST["search"])) {
print json_encode(['type'=>'1']);
}else{
$seValue = "%{$_POST['search']}%";
$querySel = "SELECT * FROM gallery WHERE galleryTitle LIKE :title OR date LIKE :dat";
$stmtquerySel = $conn->prepare($querySel);
$stmtquerySel->bindParam('title',$seValue);
$stmtquerySel->bindParam('dat',$seValue);
$stmtquerySel->execute();
if ($stmtquerySel->rowCount() == 0) {
print json_encode(['type'=>'2']);
}else{
$galleryGrid = "";
while ($rowQuerySel = $stmtquerySel->fetch()) {
$id = $rowQuerySel['galleryId'];
$image = $rowQuerySel['image'];
$title = $rowQuerySel['galleryTitle'];
$date = $rowQuerySel['date'];
$galleryGrid .= "<div class='col-lg-4 col-sm-6'>
<div class=''>
<a href='gallerydetails.php?id=$id'>
<img src='img/$image' width='100%'>
<div>Event Name:$title</div>
<div>Date :$date</div>
</br></br>
</a>
</div>
</div>
";
}
$galleryGrid .="<div class='col-md-11 text-center'>
<button type='submit' class='btn btn-primary btn-lg' onClick=location.href='gallery.php'>Back</button>
</div>";
print json_encode(['type'=>'3', 'data'=>$galleryGrid]);
}
}
when I try it on localhost it run , but when upload to server then will get 500 internal error
Use this
print json_encode(array('type'=>'3', 'data'=>$galleryGrid));
instead of
print json_encode(['type'=>'3', 'data'=>$galleryGrid]);
Before I ask this question, I have already referred to the example of this question. However, it seems doesn't work. Without using ajax, I can get my post deleted but after implement ajax, the deleteAtc.php seems to be not working.
My delete page code (delete.php)
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> Delete<br />
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = <?php echo $article['article_id']; ?>;
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id"+id+,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
<div id="success"></div><br />
<?php } ?>
While my deleteAtc.php code:
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
echo "Article deleted";
}
}
?>
What I'm trying to do here is to delete the record without redirect to deleteAtc.php, it will remove out the record and replace Article Deleted
May I know where did I go wrong in ajax side?
Please refer below for updated question
Based on the answer below, here is my updated code:
delete.php
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
deleteAtc.php
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
Somehow, if I delete two record at a time, only the first record echo the result, the second result deleted doesn't echo out the result.
Am wondering, possible to add jquery animation to .show the success message and .hide the record deleted?
First of all IDs are not meant to be duplicated, use class selector instead. Also you could make use of custom data attributes to store the id of the article.
Try
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
Script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
And in server side
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
The above script won't work you have to change like below. You are repeating the same identifier function again and again. Keep the jquery script out of foreach loop. You have to add the class property with the article id.
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> <a href="#" id="link" class='<?php echo $article['article_id']; ?>' >Delete</a><br />
<div id="success"></div><br />
<?php } ?>
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = $(this).prop('class');
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+id,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
You create several links with id="link". ID must be unique.
You have to write
id="link<? echo $article['article_id']; ?>"
as well as
$('#link<? echo $article["article_id"]; ?>').click(function() {...})
<script language="javascript">
$(document).ready(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this record? There is NO undo!"))
{
$.ajax({
type: "GET",
url: "products/delete_record.php",
data: info,
cache: false,
success: function(){
setTimeout(function() {
location.reload('');
}, 1000);
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
//location.reload();
});
});
</script>