I am trying to use AJAX to dynamically delete a record from the database through the front end site, I have the code but when I click the delete button nothing happens, there is connection to the database I just cannot find the mistake in the code, all the code files are linked to one another.
The table I want to delete a record from is called recipes.
HTML
<div id="recipecards2" class="row">
<div class="col-sm-3">
<div id="recipecards" class="card">
<div class="card-body">
<p>
<button type="button" id="deletebutton" class="btn btn-outline-danger" input type="submit" name="recipe_delete" data-id="<?php echo $recipe['recipe_id']; ?>">
<i style=color:black; class="fa fa-trash-o"></i> Delete Recipe </button> </a>
</p>
</div>
</div>
<br>
</div>
Ajax PHP code
<?php
require_once('../includes/db.php');
if($_POST['itemid']){
$query = "DELETE FROM recipes WHERE itemid= $recipe_data['recipe_id'];";
$result = $DBH->prepare($query);
$result->bindParam(':itemid', $_POST['itemid']);
$result->execute();
echo $_POST['itemid'];
}
?>
Javascript
$('#recipecards2').on('click', '#deletebutton', function() {
// var that = this;
var itemid = $('#recipecards').attr('data-id');
var request = $.ajax({
url: "ajax/removeItemsFromList.php",
type: "post",
data: { itemid : itemid}
});
// If we're successfull!
request.done(function (response, textStatus, jqXHR){
$('#recipecards2 > #recipecards[data-id="'+response+'"] ').remove();
});
});
Firstly, your issue is that you are using named parameters incorrectly, you are prepareing your query, yet at the same time you are passing a value directly to it.
Change,
$query = "DELETE FROM recipes WHERE itemid= $recipe_data['recipe_id'];";
To,
$query = "DELETE FROM recipes WHERE itemid = :itemid;";
Secondly, if you are using the data-* properties, consider using the respective .data() function too.
Thirdly, when you do an AJAX request and it doesn't go right, open your browser console and check the response of that request. That generally should point you in to the right direction.
Fourthly, your HTML for your button is malformed, take a look at your button code,
<button type="button" id="deletebutton" class="btn btn-outline-danger" input type="submit" name="recipe_delete" data-id="<?php echo $recipe['recipe_id']; ?>">
Notice how you have a button/input mix? Pick one, you don't need to have both.
Related
I am making a forum-like website in php and I added a button inside each question container to delete questions on the forum. I am looking for a way to make a popup appear when the user clicks the delete button. I am using bootstrap and I found a popup modal on the bootstrap website. With my current code, the popup appears when the button is clicked and it asks the user to confirm that he wants to delete his question. The problem is that I don't know how to get the ID of the question the users wants to delete so after I can delete it in my MySQL database.
This is my current button and it is inside a php echo '...'
<div class="col-1" title="delete your comment"><button name="delmsgbtn" class="btn-reseter" type="button" data-bs-toggle="modal" data-bs-target="#delmsg">delete</button></div>
And this is the popup modal from bootstrap that shows up when button is clicked
<div class="modal fade" id="delmsg" tabindex="-1" aria-labelledby="delmsgLabel" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="delmsgLabel">Are you sure you want to delete this message?</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">cancel</button>
<button type="button" class="btn btn-danger">delete</button>
</div>
</div>
</div>
</div>
I had the idea to redirect the user to the same page but with the url containing the question id, so after I can have it using the get method. So I modified the button by adding a redirection.
New button also inside a php echo that is why the backslash
<div class="col-1" title="delete your comment"><button name="delmsgbtn" class="btn-reseter" onclick="location.href = \'course.php?courseid='.$_GET["courseid"].'&quesid='.$idQues.'\';" type="button" data-bs-toggle="modal" data-bs-target="#delmsg">delete</button></div>
But when doing this, the page refreshes and the popup disappears. Can you help me.
First, modify your modal open button. Should be something like this
<button class="btn-reseter delmsgbtn" data-comment_id="<?= PHP_COMMENT_ID ?>">delete</button>
Be sure to replace PHP_COMMENT_ID with an actual PHP variable that holds the comments ID.
Replace the "delete" button in the modal with a form.
<form method="POST" action="PHP_PROCESS_SCRIPT">
<input type="hidden" name="comment_id" id="comment_id_input"/>
<button type="submit" class="btn btn-danger">delete</button>
</form>
Make sure that PHP_PROCESS_SCRIPT points to the PHP script to process the comment deletion. Also, if applicable, make sure in this script that the user who is deleting the comment is actually allowed to.
Create a click handler to open the modal, instead of inline attributes.
<script>
$('.delmsgbtn').on('click', function() {
//update #comment_id_input in the popup form,
//based on data-comment_id added to the button from the first snippet
$('#comment_id_input').val($(this).data('comment_id'));
$('#delmsg').modal('show'); //open the modal
});
<script>
When the form is submitted, the PHP script you hooked up will get a value $_POST['comment_id'].
Alternatively, you could make an ajax call from a click handler attached to the delete button inside the modal. This is better if you want to prevent a page refresh. First, modify the delete button like this
<button id="delmsg_submit" type="button" class="btn btn-danger">delete</button>
Then, add some click handlers
<script>
var active_comment_id = null;
$('.delmsgbtn').on('click', function() {
//update active_comment_id,
//based on data-comment_id added to the button from the first snippet
active_comment_id = $(this).data('comment_id');
$('#delmsg').modal('show'); //open the modal
});
$('#delmsg_submit').on('click', function() {
if(active_comment_id) {
//send ajax call
}
});
<script>
I would put the id of the element with php
like
<button id="element-id-<?php echo $id ?>" class="myBtn" >
then i would use a javascript function to do execute the call on database
<script>
const btn = document.querySelector('.myBtn')
btn.addEventLIstener('click', () => {
const elementId = this.id //then remove the 'element-id-' from the value
const data = { id: elementId }
fetch( URLforBackend, {
method: 'post',
headers: {
'Content-Type': 'application/json'
}
body: JSON.stringify(data)
})
</script>
this will give to your backend the id.
in php, in there, just do the deletion
So, right now I am trying to make it so that an AJAX post request can trigger this conditional statement:
if(isset($_POST['purse'])) {
if($_POST['purse'] == true) { <---- Removed
if($nexttime <= time()) {
/* Some DB queries etc.. */
$output = array();
array_push($output, "<div class='alert alert-success'>You are successful!</div>");
echo(json_encode($output));
} else {
/* Other stuff... */
}
}
/* Echos work here */
}
And so far I have tried this:
$(document).ready(function() {
$('#purse').click(function() {
$.ajax(
{
type : "POST",
url: "petty.php",
data: {purse: 'true'},
dataType: 'json',
success: function(data) {
alert(data);
}
});
});
});
But that doesn't seem to trigger it. This is all for an effort to make it so the page executes whatever it is supposed to, depending on which button the user clicks, without refreshing the page and I heard AJAX is the way to go for that, but I honestly can't figure it out and have tried tutorials but they don't do what I am trying to do, from what I have seen.
Form:
<form action="petty.php" method="post">
<div class="subheading mb-5 text-center"><br>Steal a few purses.
<button type="submit" name="purse" id="purse" class="btn btn-dark center-block">Submit</button>
<div class="subheading mb-5 text-center"><br>Forge checks.
<button type="submit" name="checks" id="checks" class="btn btn-dark center-block">Submit</button>
<div class="subheading mb-5 text-center"><br>Steal cars.
<button type="submit" name="cars" id="cars" class="btn btn-dark center-block">Submit</button>
</form>
EDIT: Well, my issue is that I am trying to push all messages, that the user will be able to see upon clicking a button, into an array and using echo(json_encode($output)) to push it all to AJAX so that it can be outputted to the browser, but it doesn't seem to be working.
You're using
$.ajax({
url: url,
data: {'purse' : purse},
type : "POST"
});
but we don't see the definition of 'url' or 'purse' anywhere. Did you debug it using Chrome/Firefox Developer Tools and check if it actually sends the ajax request?
Also, you should first check the existence of the ['purse'] key in your php code and then check validity. You're only checking existence, so the if statement will be entered any time you send the ajax, regardless of whether 'purse' actually contains anything.
I make the cart with a separate page. When view cart button is clicked I load the php file of the cart. Where I loop the cart session variable array and show in the page. But, when the user press delete button of an item it should be deleted and not shown after in the cart page. Now, how can I automatically update the cart page without reloading the page?
I need some idea how can I implement this?
loop part
<?php foreach($_SESSION['cart'] as $result)
{
?>
delete button
<div class="col-sm-6">
<div class="row">
<div class="col-sm-2">
<h6><strong><?php echo $result['price']; ?><span class="text-muted"> x</span></strong></h6>
</div>
<div class="col-sm-4">
<input type="text" class="form-control input-sm" value=<?php echo $result['quantity']; ?>>
</div>
<div class="col-sm-2">
<button type="button" class="btn btn-link btn-sm">
<span class="fa fa-trash"> </span>
</button>
</div>
</div>
</div>
full source code here
Edit 1
suppose I get the page by ajax call
$.ajax(
{
url: 'makeCartPage.php',
type: 'POST',
success: function(msg)
{
//here to code to show the new cart page/information
},
error: function()
{
console.log('cart error');
}
});
But, there was a challenge to show the ajax return data.
There are a couple ways to do this, but one way is to not refresh the list, but rather hide the item you delete, so add a class to the top-level row wrapper class like product-wrapper or what-have-you:
<div class="row product-wrapper">
When you click the x button, you run the ajax, update the session on the makeCartPage.php page, and on success you traverse the DOM using $(this) and hide the product-wrapper class. Something like:
$('.text-muted').on('click',function(){
// Isolate the clicked button
var deleteButton = $(this);
// Run ajax to remove the item out of the session
$.ajax({
url: 'makeCartPage.php',
type: 'POST',
data: {
"id": /* get your product id here however you are able so you can remove from the session */
},
success: function(response) {
// You want to send back a delete success response when you actually
// remove it from the session. If true, do something similar to this
deleteButton.parents('.product-wrapper').fadeOut('fast');
},
error: function(){
console.log('cart error');
}
});
});
This should be enough info to get you started. Here is a fiddle of the hiding fx:
https://jsfiddle.net/efL891mu/
I'm working on add to compare feature of a website,so on current page there are some results which have a checkbox named add to compare attached.
So when user click on add to compare checkbox the selected result get appended to one compare box div and this process go on.
my problem is,when user want to uncheck or remove the selected result from compare div box he should be able to remove it.
Here's is my code which i have done till yet
html
<div id='compare_box'>
<form action="compare_results.php" method="POST">
<div id='result'>
</div>
<button id="compare_submit" type="submit" class="btn btn-primary btn-sm">compare</button>
</form>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<h4><small><?php echo $title; ?></small></h4>
<br>
<div class="features">
<div id="compare_feature">
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">add to compare
</div>
<button class='btn btn-sm btn-info favourite_feature' value="<?php echo $id;?>">add to favourite</button>
</div>
</div>
</div>
css
#compare_box
{
display: none;
}
ajax call
$(".compare").change(function() {
if(this.checked) {
$('#compare_box').show();
var check = $(this).val();
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : "JSON",
data:{value : check},
success: function(data)
{
console.log(data);
console.log(data.id);
var output = "<div class='col-md-3 photo-grid' style='float:left'>";
output += "<div id='course_title' class='well well-sm'>";
output += "<h4>"+data.title+"</h4>";
output+="<textarea class='hidden' id='hidden_title' name='course_title[]' value=>"+data.title+"</textarea>";
output+="</div>";
output+="<input type='hidden' id='hidden_id' name='course_id[]' value="+data.id+">";
output+="</div>";
$('#result').append(output);
}
});
}
});
PS: I'm trying to implement something like this
What is '#compare_box' ? Is it the element that appears when the checkbox disappear (in your exemple at 'your selection')?
Then bind an action on '#result' - precise something that can link your element to check box like an id (when you prepare your html in ajax response).
$('#result').on('click', function() {
$($(this).data('id')).prop('checked', false); // uncheck it
$(this).remove();
});
Do the same for when you uncheck a checkbox (find the element with data-id of your check box and remove it)
EDIT : it's not the perfect code to make it work, you might adapt depending on where you bind click or place the data-id
i have this bit of html.
(Link at bottom)
Its output of php code for status updates, it has view comments and post comment link, the post comment link uses jquery to add a textarea and submit button below that status update. and the view comments shows the comments to that status update below that status update.
So i use php looping so there will be obviously more than 1 status updates at most times(depends on how much friends users have) so i cant have an element like 'textelement', i will need to have elements like 'textelement1' and 'textelement2'
So i used php to add the id of the status update in the end of the links like _id so the element id becomes view_comments_1.
So i want to use jquery to find out which element has been clicked so that i can add a text box and show comments below the right status update instead of showing it below all status updates.
HTML
<div class="wrapbg">
<span class="corners-top"><span></span></span>
<div id="content"><br/>
Whats new?
<hr class='hr1'>
<div class='stbody' id='stbody'>
<div class='stimg'>
<img src='uploads/profile_pics_small/Anonymous_Blueprint_Wallpaper_by_co.jpg' /></img>
</div>
<div class='sttext'>
Welcome yoall!!
<div class='sttime'>By LUcase</div>
<br><br>
<a href=''>0 Likes</a> <a href=''>1 Dislikes</a>
</div>
<a href=''>unDislike</a> <a id='comment_now_1' href=''>Comment</a> <a id='view_comments1' data-id-1 = '1' href=''>View comments</a> <div id='emptydiv1'> </div></div>
<div class='stbody' id='stbody'>
<div class='stimg'>
<img src='uploads/profile_pics_small/wood_texture_by_pabloalvin-d1igijr.jpg' /></img>
</div>
<div class='sttext'>
hi
<div class='sttime'>By nicknick</div>
<br><br>
<a href=''>0 Likes</a> <a href=''>0 Dislikes</a>
</div>
<a href=''>Like</a> <a href=''>DisLike</a> <a id='comment_now_4' href=''>Comment</a> <a id='view_comments4' data-id-4 = '4' href=''>View comments</a> <div id='emptydiv4'> </div></div></div>
<span class="corners-bottom"><span></span></span>
</div>
JavaScript
//Gotta find out which status update we are dealing with!
jQuery("document").ready(function(){
jQuery(".likebtn").click(function(e) {
var id=jQuery(this).attr("data-id");
jQuery.post('like.php', {'id': id}, function(data) {
alert("Your like.php has been called");
}, "json");
e.preventDefault();
});
jQuery(".dislikebtn").click(function(e) {
});
//gotta figure out which status update we are dealing with!
//attache the click event to the anchor tag
$("#comment_now").live("click",function(e){
//prevent the default behaviour of following the link
e.preventDefault();
$("#comment_now").remove();
//find the textarea element, and after it, put an input tag
$(".sttext").after('<textarea id="comment_text" name="comment"></textarea> <br> <button id = "post_button" class="action greenbtn"><span class="label">Comment</span></button> <a id="cancel_comment" href="">Cancel</a> <br id="com_spacing">');
});
//gotta figure out which status update we are dealing with!
$("#cancel_comment").live("click",function(event){
event.preventDefault();
$("#comment_text").remove();
$("#cancel_comment").remove();
$("#post_button").remove();
$("#com_spacing").remove();
$("#view_comments").before('Comment ');
});
$("#view_comments").live("click", function(e){
e.preventDefault();
var id=jQuery(this).attr("data-id");
$.ajax({
url: 'query_comments.php?status_id='+id,
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=UTF-8' );
},
success: function( data ) {
$('#emptydiv').html(data);
}
});
});
});
Please help me out :)
You know that html forms can send arrays, right?
<input type="text" name="textelement[]" value="First Element" /><br/>
<input type="text" name="textelement[]" value="Second Element" /><br/>
PHP Code:
foreach($_POST['textelement'] as $somethingSomething){
echo $somethingSomething, "\n";
}
Prints out:
First Element
Second Element
add a class to to action buttons and pass the comment id as data attribute like so:
<a class="commentBtn" href='' data-commentid="1">Comment</a>
and than you can read out the id easily with jquery:
$(".commentBtn").live("click",function(e){
var id = $(this).data('commentid');
e.preventDefault();
// do something with id…
});