Deleting a row using AJAX using fadeOut - php

I am following a tutorial online on AJAX. There is a lecture on how to delete a row from a table without reloading it again.
I added a delete button for each row in my HTML table and I set its id to id="del" inside a table with an id="myTable".
I am trying to delete a row using Ajax and remove it without refresh with an animation fadeOut().
I have this Ajax script:
$("#myTable #del").click(function()
{
if(confirm("Are you sure you want to delete this row ?"))
{
var id = $(this).closest('tr').attr('id');
var row = $(this).closest('tr');
$.ajax
({
url: 'delete_row.php',
type: 'POST',
data: {dataID: id},
dataType: "text",
success:function(data)
{
console.log(id);
if(data=="deleted")
{
row.fadeOut('slow', function() {$(this).remove();});
}
}
});
}
});
In the console, I see the correct id displayed, but neither does it disappear from the table nor get deleted from database.
Here is the PHP code:
try
{
$id = $_POST['dataID'];
$delete = "DELETE FROM employee WHERE id = :d";
$delStmt = $conn->prepare($delete);
$delStmt->bindValue(":id", $id);
$delStmt->execute();
echo "deleted";
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
}
The instructor code is working properly, and I can't see where my error is so it isn't working for me. Any help is appreciated.

Bind value hasn't same name in the PDO request
$delete = "DELETE FROM employee WHERE id = :d";
$delStmt->bindValue(":id", $id);

Related

Delete data from table with AJAX and PHP

Can you explain me where is the problem? Because I lost all my hope for this...
Insert and load work but delete not... When I remove if statement from delete, it says id is undefined index. But why it should be undefined when I define it in var id = $(this).data("id3"); I think the problem will be somewhere in select.php with a button.
I have lack of experience with AJAX so I ask you for help with this problem.
Thank you for response. (sorry for the language)
Index.php
$('.btn_delete').on('click', function()
{
var id = $(this).data("id3");
if (confirm('Naozaj zmazat ?')) {
$.ajax({
url: 'delete.php',
type: 'POST',
data: {delete: 1, id: id},
success: function(data)
{
alert(data);
fetch_data();
}
});
}
});
delete.php
if (isset($_POST['delete'])) {
include("db.php");
$id = mysqli_real_escape_string($conn, $_POST['id']);
$sql = "DELETE FROM suciastka WHERE id_suciastka = '".$id."'";
if (mysqli_query($conn, $sql)) {
echo "Deleted";
}
}
And here is my select.php
include("db.php");
$output = "";
$sql = "SELECT * FROM suciastka";
$result = mysqli_query($conn, $sql);
$output .= "
<div class='table-responsive'>
<table class='table table-bordered'>
<tr>
<th>ID</th>
<th>NAME</th>
<th>NUMBER</th>
<th>PLACE</th>
<th>DESCR</th>
<th>ACTION</th>
</tr>";
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result))
{
$output .= "
<tr>
<td>".$row['id_suciastka']."</td>
<td>".$row['name_suciastka']."</td>
<td>".$row['number_suciastka']."</td>
<td>".$row['place_suciastka']."</td>
<td>".$row['descr_suciastka']."</td>
<td><button type='button' name='delete_btn' data-id3='".$row['id_suciastka']."' class='btn btn-danger btn_delete'>Delete</button></td>
</tr>";
}
}
$output .= "</table>
</div>";
echo $output;
Let's debug this code step by step :
First of all, we should check the content of $_POST in your PHP code :
die(var_dump($_POST)); at the top of delete.php.
Do you see your id?
If yes, then... Just be sure you typed the right index name :)
If no, we have to get closer to the browser :
Open your code inspector (Ctrl+Maj+I on chrome), get to the Network panel. When you fire your AJAX query, a new line will apper! Just click on it, you will find in the "Headers" section all data about request/Response, and at the bottom you'll find the data you sent!
Do you see your id?
If yes, then there is code you didn't show us that do whatever something that erase your data or something ^^
If no, let's take a look in the javascript :
Still in the Inspector, open the "source" pannel and find your index.php, and more precisely the code you sent us.
Just add a marker after your var id = ... by clicking on the line numbers.
Fire your ajax request again. You will be able to see your value of id.
Is the value correct? If yes... well boy, we have to keep digging together!
If no (it is "undefined" or "null"), then that's why the browser doesn't send it!
In this case, you have to check the value of $row['id_suciastka'], for exemple by using a var_dump($row); at the begining of your loop in index.php.
If nothing seems to work, then we have to get more informations on the problem!
Hope it helps! :)
I think your button is not in the DOM
You can try:
$(document).on('click', '.btn_delete', function() {})
$('.btn_delete').on('click', function(){
var id = $(this).data("id3");
if (confirm('Naozaj zmazat ?'))
{
$.ajax({
url: 'delete.php',
method: 'POST',
data: {delete:1, id:id},
success: function(data){
alert(data);
fetch_data();
}
});
}
});
Replace type with Method in ajax request.
For start, you can console.log id before you send a post request, so try
$('.btn_delete').on('click', function(){
var id = $(this).data("id3");
console.log(id); // <-- log ID here
if (confirm('Naozaj zmazat ?'))
{
$.ajax({
url: 'delete.php',
type: 'POST',
data: {delete:1, id:id},
success: function(data){
alert(data);
fetch_data();
}
});
}
});
If you get something there, then hit F12 in Chrome or Firefox and in dev tools, go to network tab and inspect http request to your PHP and in "headers" tab check "Form data" section of request (body of http request).
If you get ID and delete properties there, then your JS is correct and you should look for bug in PHP.
Best way to start on that would be to var_dump whole $_POST array. So:
var_dump($_POST);
if (isset($_POST['delete'])) {
include("db.php");
$id = mysqli_real_escape_string($conn, $_POST['id']);
$sql = "DELETE FROM suciastka WHERE id_suciastka = '".$id."'";
if (mysqli_query($conn, $sql))
{
echo "Deleted";
}
}

I am trying to write an UPDATE query in codeigniter but for some reason it's inserting a new record with default values

I am trying to update an existing message. A message has a message_id, category, subject and the message. Upon clicking on edit, an AJAX call is made ...
Here's my AJAX call from .js file (VIEW)
if(checkEditMessage()){ // checkEditMessage is to check for validation
console.log("EDIT");
var cat_id = $("#cat_id").val();
var commentsubject = $("#commentsubject").val();
var chat_post_message = $("#chat_post_message").val();
$.ajax({
url: base_url + "chat/editMessage",
async: false,
type: "POST",
data: {
"v_id" : id,
"v_cat_id" : cat_id,
"v_commentsubject" : commentsubject,
"v_chat_post_message" : chat_post_message
},
error: function(err){
console.log(err);
},
success: function (result) {
console.log(result);
}
});
}
Here's my chat.php (CONTROLLER)
function editMessage(){
$posted_data = $this->input->post();
if(isset($posted_data) && !empty($posted_data))
{
$id = $posted_data['v_id'];
$cat_id = $posted_data['v_cat_id'];
$commentsubject = $posted_data['v_commentsubject'];
$chat_post_message = $posted_data['v_chat_post_message'];
$data = $this->chat->updateMessage($id, $cat_id, $commentsubject, $chat_post_message);
echo $data;
}
}
Here's my (MODEL)
function updateMessage($id, $cat_id, $commentsubject, $chat_post_message){
$data=array('cat_id'=>$cat_id,'subject'=>$commentsubject,'message'=>$chat_post_message);
$this->db->where('message_id',$id);
$this->db->update('chat_message',$data);
$err = $this->db->_error_message();
if(empty($err))
{
return "EDIT COMPLETE";
}
return false;
}
Your question is not totally clear, because I don't see any insert, and in order to insert it's really needed the insert clause in your query. I can only tell you some improvements you may want to do.
Which version are you using of codeigniter? Because I don't see you using the word _model which is necessarily.
$message['v_id'] = $posted_data['v_id'];
$message['v_cat_id'] = $posted_data['v_cat_id'];
$message['v_commentsubject'] = $posted_data['v_commentsubject'];
$message['v_chat_post_message'] = $posted_data['v_chat_post_message'];
// `chat_model` and not `chat`
$result = $this->chat_model->updateMessage($message['v_id'], $message);
On the other hand, all you need to do in your model function is
public function updateMessage($id, $data)
{
$this->security->xss_clean($data);
$this->db->where('message_id', $id)
->update('chat_message', $data);
return empty($this->db->_error_message());
}
In you ajax change this
url: "<?php echo base_url() ?>chat/editMessage",
async: false,// remove this
data: {
"v_id : id,
v_cat_id : cat_id,
v_commentsubject : commentsubject,
v_chat_post_message"} ,
and your model and controller looks ok
You can try the following:
Make sure your message_id is getting posted properly. i.e. echo $posted_data['v_id']; in editMessage() to see if the correct value is being received.
Make sure the id you are trying to update exists, and that message_id in your database is the PRIMARY KEY field.

Ajax update table with php content

How to make an animated table only animate when a new record is added to the database.
Ajax/Js (in index.php):
$.ajax({
url : 'Not sure what goes here?',
data : {Not sure what goes here?},
dataType : 'application/json', // Is this correct?
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
var newitem = function(response){
var item = $('<div>')
.addClass('item')
.css('display','none')
.text(response)
.prependTo('#scroller')
.slideDown();
$('#scroller .item:last').animate({height:'0px'},function(){
$(this).remove();
});
}
My php (latest.php):
include ('db.php');
$sql2 = "SELECT * FROM `feed` ORDER BY `timez` DESC";
$res2 = mysql_query($sql2) or die(mysql_error());
while($row3 = mysql_fetch_assoc($res2)){
$user = $row3['username1'];
$action = $row3['action'];
$user2 = $row3['username2'];
echo ''.$user.''.$action.''.$user2.'<br>'; // Needs to be a json array?
I can't get this to work, here's how the table operates http://jsfiddle.net/8ND53/ Thanks.
$.ajax({
url : your_php_file.php',
data : {data you'r going to send to server}, // example: data: {input:yourdata}
success: function(response) {
$('#table_id').append('<tr>'+response+'</tr>'); // response is the date you just inserted into db
}
});
in your_php_file.php:
add the item into db
echo that inserted data # if you echo, then you can catch this with ajax success function then you append it into your table.
try to fill as below:
$.ajax({
type: "post"
url : 'locationOfphpCode/phpCode.php',
data : {data you want to pass}, //{name: "dan"}
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
in your php code you need to receive the data you have passed from the ajax call:
<?php
$name = $_POST['name'];
...
?>
you may add some validations in your php code.
hope this will help you.
the example you have given is using setInterval(newitem, 2000)
so you have to call ajax function on some fixed interval.

Duplication of entry when sharing content

When I click on share on a users link..It shares that post fine, yet it posts it twice. I've checked firebug and when clicked (Once) it shows up two POST requests, inserts two posts to the database and then shows them in the users feed.
I really don't understand where I'm going wrong.
SHARE LINK
echo'<a class="sharelink" title="Share '.$poster_name['fullusersname'].'s status" href="#"
data-streamitem_creator='.$streamitem_data['streamitem_creator'].'
data-streamitem_target='.$_SESSION['id'].'
data-streamitem_content='.$streamitem_data['streamitem_content'].'
data-streamitem_type_id=4>Share</a>';
AJAX
$(document).ready(function() {
$('.sharelink').click(function(e) {
e.preventDefault();
var streamitem_creator = $(this).data('streamitem_creator');
var streamitem_target = $(this).data('streamitem_target');
var streamitem_content = $(this).data('streamitem_content');
var streamitem_type_id = $(this).data('streamitem_type_id');
$.ajax({
type: "POST",
url: "../include/share.php",
data: {
streamitem_creator: streamitem_creator,
streamitem_target: streamitem_target,
streamitem_content: streamitem_content,
streamitem_type_id: streamitem_type_id
},
success: function(data) {
$(".usermsg").html(data);
}
});
});
});​
SHARE.php
<?
session_start();
require"load.php";
if(isset($_POST['streamitem_type_id'])&isset($_POST['streamitem_creator'])&isset($_POST['streamitem_content'])&isset($_POST['streamitem_target'])){
user_core::create_streamitem(4,$_SESSION['id'],$_POST['streamitem_content'],1,$_POST['streamitem_creator']);
}
?>
LOAD.PHP
public function create_streamitem($typeid,$creatorid,$content,$ispublic,$targetuser){
global $mysqli;
$content = $content;
// $content = strip_tags($content);
if(strlen($content)>0){
$insert = "INSERT INTO streamdata(streamitem_type_id,streamitem_creator,streamitem_target,streamitem_timestamp,streamitem_content,streamitem_public) VALUES ($typeid,$creatorid,$targetuser,UTC_TIMESTAMP(),'$content',$ispublic)";
$add_post = mysqli_query($mysqli,$insert) or die(mysqli_error($mysqli));
$last_id = mysqli_insert_id($mysqli);
if(!($creatorid==$targetuser)){
$fromuser= rawfeeds_user_core::getuser($creatorid);
$_SESSION['id']==$content;
}
return;
}else{
return false;
}
I can't see any problem.. By any chance, don't you have that $('.sharelink').click handler registered twice within your page?

jQuery ajax delete script not actually deleting

I have a little personal webapp that I'm working on. I have a link that, when clicked, is supposed to make an ajax call to a php that is supposed to delete that info from a database. For some unknown reason, it won't actually delete the row from the database. I've tried everything I know, but still nothing. I'm sure it's something incredibly easy... Here are the scripts involved.
Database output:
$sql = "SELECT * FROM bookmark_app";
foreach ($dbh->query($sql) as $row)
{
echo '<div class="box" id="',$row['id'],'"><img src="images/avatar.jpg" width="75" height="75" border="0" class="avatar"/>
<div class="text">',$row['title'],'<br/>
</div>
/*** Click to delete ***/
x</div>
<div class="clear"></div>';
}
$dbh = null;
Ajax script:
$(document).ready(function() {
$("a.delete").click(function(){
var element = $(this);
var noteid = element.attr("id");
var info = 'id=' + noteid;
$.ajax({
type: "GET",
url: "includes/delete.php",
data: info,
success: function(){
element.parent().eq(0).fadeOut("slow");
}
});
return false;
});
});
Delete code:
include('connect.php');
//delete.php?id=IdOfPost
if($_GET['id']){
$id = $_GET['id'];
//Delete the record of the post
$delete = mysql_query("DELETE FROM `db` WHERE `id` = '$id'");
//Redirect the user
header("Location:xxxx.php");
}
Ah just spotted your error, in the href you're generating you're not setting the id attribute. It should be something like:
x
Of course that's just an immediate example, you must escape these kinds of things but this should let you access the item in jQuery.
You may want to modify your delete script to not just redirect after the DB query. Since it's being called via AJAX, have it at least return a success/error code to the javascript:
// can't return $delete unconditionally, since *_query() returns an object
if ($delete) {
return(json_encode(array('code' => 1, 'msg' => 'Delete succeeded')));
} else {
return(json_encode(array('code' => 0, 'msg' => 'Delete failed: ' . mysql_error()));
}
It's bad practice to assume a database call succeeded.

Categories