Removing contents with Ajax is a useful tool to have in any web designers kit. Using a few lines of jQuery we can remove a div and simultaneously remove a record from the database with Ajax. In the download and demo you’ll see a small red cross to the right of each comment. Clicking the cross will remove the comment div with a slide up animation which will remove the div. click the image below to check out the demo.
We start by writing the dom ready function to simply hide our loading message div which is used as a visual representation to the user when we go to delete a comment.
$(document).ready(function() {
$('#load').hide();
});
The next block of code is what essentially does the hard work. we have a .click function to start with that when run fades in the ‘#load’ div to show the user that we’re deleting the item.
We then set the variable ‘commentContainer’ which is set to represent the parent element to ‘.delete’ which is the div ‘.box’ as show in the image below.
var commentContainer = $(this).parent();

The variable ‘id’ is then set with the value of the delete button id which would could be the id of the row in the database that you want to delete. This is then posted to the page delete.php. once the Ajax request has been made and a response has been acknowledged we then slide up and remove the div ‘.box’ and fade out the loader. Finally ‘return False;’ is added to the end of the function in order to stop the page from refreshing as we are using an ‘a tag’.
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
I have left the delete.php page for you to add your own database connection script and query in order to use the code for your own needs. If however you have any questions on how to set this up please let me know below.
The complete code along with images is available to download below.
Pingback: 40 Smart Ajax Tutorials and Techniques | Smash Materials
Pingback: ajax tutorials and techniques - Mnovi
Pingback: 30 Fresh AJAX Tutorials And Techniques | A1 Web Design Team :: Blog
Pingback: 30个精选Ajax技术教程 | 石家庄网络公司_网站建设公司_石家庄网站制作价格
Pingback: 10 New jQuery AJAX Techniques with Source Code | Web Insight Lab
Pingback: 我收集到的最新的AJAX教程和技术(上篇) | 编程·早晨
Pingback: Best and Free Tutorials on Ajax and Techniques | Designs Madness
$.ajax can also be use in recursion?
and how to do it
Спасибо.
Very nice. You good programmer!
Valentin from Ukraine.
Hey i am trying to use this chunk of code with coldfusion. But i don’t have much knowledge about ajax. on your javascript you are passing ‘id’ attribute with a value, but if i have to pass another value, how do i do that?
lets say my data base needs to match with two value such as …
delete from #book_contact#
where contact_id =
and booking_id =
in the following code, how can i pass another value or attribute to match with ‘id’ and ‘bid’:
$(document).ready(function() {
$(‘#load’).hide();
});
$(function() {
$(“.delete”).click(function() {
$(‘#load’).fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr(“id”);
var string = ‘id=’+ id ;
$.ajax({
type: “POST”,
url: “delete.cfm”,
data: string,
cache: false,
success: function(){
commentContainer.slideUp(‘slow’, function() {$(this).remove();});
$(‘#load’).fadeOut();
}
});
return false;
});
});
let me know if you can help
Hi.
Works great but when the list is empty – it shows 1 Jan 1970 text as am populating a date from the database. But as the list is empty – it shouldn’t show anything on the list but at the runtime, i am getting this value added to the list when the list is empty. i.e. 1 jan 1970. Am sure this is coming somewhere from jquery. Do you know, what’s going on here and how can i sort that out?? thanks
James you are right it work with $_GET and $_REQUEST.
Thanks for helping me.
very nice script.it solve my problem.
Thank
Hi.
Is it possible to add a confirmation alert to this?
Thanks.
wow ![]()
Nice jquery script
Rach – debug. Check can you delete from database without jquery, then add jquery on top of that.
To papermashup – Please fix the script. I take that you have had some hosting changes or something like that, because WordPress has replaced your special characters, which ruins the code a bit
Hi,
I am trying to use this code to delete a record from MySql database using PHP. I tried different ways but when I refresh the page I again see the deleted records. Can I get some help on this?
Thanks.
Nice Job!!!!
Bravo!
wow..this is the most amazing steps to get the hand dirty….thanks for sharing this….
Ashley, I was going to zip up my code and send it, but there’s no reason to. If I copy the source code out of the demo html page, and save it. It does not display the way the demo page does. What am I missing?
Ashley, I can’t understand why my tests of the script look mangled. Even when I test your html file, it looks like the styles aren’t applied correctly. The box elements don’t line up, the contents are not inside them. It looks nothing like your example.
how to use more variables?
Hi! really good work, but well, i need help with the delete.php page, i’m a begginer and i really be thanksful if you help with it..
Regards!
Rodrigo.
Great tutorial, but I did notice the class “clear” was never added into the css.
div.clear {
clear: both;
}
Hi
I am new in jquery so thank you for that as it helps me lot.
Regards
thanks to this tutorial.. It’s works fine..
this code works perfect! smooth & fast ![]()
just one question: maybe it would be handy if there’s a prompt to ask the user if they’re certain to delete the thing?
Nice share, just fine tuned it a bit,. and wala,,.. it just works like a charm. Thanks. two thumbs up.
this is good, but seems to be slow, isn’t it so?
Great tutorial! i cant seem to get the download to work?
hello, the code works great, I’m learning jquery and I have a question:
because the code is enclosed in a function?
$ (document). ready (function () (
$ ( ‘# load’). hide ();
));
$ (function () (
$ ( “. delete.”) click (function () (
$ ( ‘# load’). fadeIn ();
commentContainer var = $ (this). parent ();
var id = $ (this). attr ( “id”);
var string = ‘id =’ + id;
$. ajax ((
type: “POST”,
url: “delete.php”
data: string,
cache: false,
success: function () (
commentContainer.slideUp ( ‘slow’, function () ($ (this). ();}); remove
$ ( ‘# load’). fadeOut ();
)
));
return false;
));
));
and not like this:
$ (document). ready (function () (
$ ( ‘# load’). hide ();
$ ( “. delete.”) click (function () (
$ ( ‘# load’). fadeIn ();
commentContainer var = $ (this). parent ();
var id = $ (this). attr ( “id”);
var string = ‘id =’ + id;
$. ajax ((
type: “POST”,
url: “delete.php”
data: string,
cache: false,
success: function () (
commentContainer.slideUp ( ‘slow’, function () ($ (this). ();}); remove
$ ( ‘# load’). fadeOut ();
)
));
return false;
));
));
I do usually use the second form, but is there any difference?
pd: sorry if a silly question but I want to know the difference or if there is any disadvantage
PD2: sorry for my English, use google translator xD
gracias mi rey te amoooooooooooo
Pingback: 30 Fresh AJAX Tutorials And Techniques » Shai Perednik.com
Pingback: 29 Fresh, Creative AJAX Tutorials And Techniques | Seventy Seven
i try to insert this delete option into the jquery UI sortable portlets
The sortable portlet contents i got to work with a blocks manager system.
Jquery offers me to add an icon into the portlets header : “ui-icon-closethick”
I managed to get the delete function to work with the provided class from here.
But as you might figured out by above information.
I try to get this function working with the provided icon in the portlet header
Here is my javascript:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "server_items_reorder.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
}
});
return false;
});
});
$(function() {
$(".column").sortable({
connectWith: '.column',
update: savelayout
});
$(".portlet").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
.find(".portlet-header")
.addClass("ui-widget-header ui-corner-all")
.prepend('')
.end()
.find(".portlet-content");
$(".portlet-header .ui-icon").click(function() {
$(this).toggleClass("ui-icon-plusthick").toggleClass("ui-icon-minusthick");
$(this).parents(".portlet:first").find(".portlet-content").toggle();
}).click();
$(".column").disableSelection();
});
And a little php:
sql_query($sql);
while(list($bid, $bkey, $title, $url, $bposition, $weight, $active, $blanguage, $blockfile, $view) = $db->sql_fetchrow($result)) {
?>
<div class="portlet" id="">
<a href="#" id="" class="delete">x
I really hope to get this working
Hello Ashley,
Great article !
I have made a “Post a comment” thing, and used this article to make the delete function.
There is no problem when iam loader the page… then the delete thing works perfect.
But when iam pressing delete on a comment just added, it doesn’t work.
Here is my delete part:
$(‘.deletecomment’).click(function() {
var id = $(this).attr(“id”);
$(‘#comment’ + id).fadeIn();
$.ajax({
url: “ajax-files/comments.php”,
data: ‘action=delete-video&id=’ + id,
type: “post”,
success: function(){
$(‘#comment’ + id).fadeOut();
}
});
return false;
});
And my add part:
$(‘input#addcomment’).click(function() {
var text = $(“textarea#commenttextarea”);
var content = $(“#comments”);
var usrid = $(“input#usrid”).val();
var id = $(“input#id”).val();
var action = $(“input#action”).val();
var t = text.val();
if (t != ”) {
text.removeClass(‘active’);
text.addClass(‘deactive’);
text.val(‘Gemmer kommentar…’);
$(‘input#addcomment’).hide();
text.attr(‘disabled’, true);
$.ajax({
url: ‘ajax-files/comments.php’,
data: ‘action=’ + action + ‘&comment=’ + escape(t) + ‘&usrid=’ + usrid + ‘&id=’ + id,
dataType: ‘json’,
type: ‘post’,
success: function (j) {
if (content.html() == ‘Der er ikke nogle kommentarer.‘) {
content.html(j.comment);
}
else {
content.before(j.comment);
}
text.removeAttr(‘disabled’);
text.val(commentText);
$(‘#commentsamount’).html(amount+1);
$(‘#comment’ + j.id).show(‘slow’);
}
});
}
else {
text.addClass(‘active’);
$(this).show();
}
});
I dont know if you can see any thing out of this… Iam totally new in jQuery, this is my first script
Thomas
anyone gotten this to work correctly? I can’t seem to get delete.php to display anything. I’ve tried passing in a variable and using a static “hello world.”
NOTHING. I even tried James explanation but it still didnt do anything.
Pingback: 10 plugins exceptionnels pour jQuery « Armel Pingault
I think this is the second post of yours I have used, always checking out how other web developers solve user interface problems. Thanks again for sharing this Ashley!
@Brad
I had the same problem – the fadeout works but never seemed to pass anything to the php script.
I solved it by changing the POST to a GET – i.e:
$.ajax({
type: “GET”,
url: “delete.php”,
data: string,
cache: false,
success: function(){
commentContainer.fadeOut(‘slow’, function() {$(this).remove();});
}
and in the delete.php file:
$id_to_delete = $_GET['id'];
Now it works…. dunno why the POST didn’t work though.
Like the script but no one has answered this question yet across the web for this script. I am able to get the fade out to work but this script seems to never call the delete php page. Any thoughts? I went as far as creating a logging file and putting logging within the delete page, and still nothing.
i apologise for the third post in a row but it seems this site is blocking php code i am trying to post.
3rd attempt:
id= START PHP
” $entry['column_name'] ”
END PHP
sorry, error in the above:
<a href="#" id=" ” class=”delete”>
Amazing tutorial thanks.
For those who are struggling here is the code you need to implement:
in the index you need to set the id of the post as the id from the database. to do this:
$idquery = “SELECT * FROM table_name WHERE column_name=’$entryid’ ORDER BY entrydate DESC LIMIT 10″ ;
$last10entries = mysql_query($idquery);
}
while ($entry = mysql_fetch_array($last10entries)){
//any other poststuff in here
<a href="#" id=" ” class=”delete”>
//to save confusion, instead of using the defualt ‘x’ to delete i am using an image.
and here is the delete.php code:
hope this helps
thanks for responding. I actually figured it out, but thanks anyway Keep up the educational goodness
Hi Ashley, Your tutorial fell right onto my screen right when i needed it. Its great. I still dont exactly understand how to implement php and mysql queries into delete.php for this to work with databases. If you can get back to me i will truly be greatful
Pingback: jQuery Ajax delete | Papermashup.com
Pingback: Twitted by jQueryLinks
Pingback: 11 JQuery tutorials for working with HTML forms | Webmaster 9
Hi Ashley,
I set up everything, but delete.php does nothing. I edited it, connected to database, but it seems to me like it doesnt have any effect. In your default delete.php file there is “echo $_POST['id']“. After clicking on X button isn’t it suppose to be printed the id value?
Can you please send me explanation?
Thanks in advance
Ile
Pingback: èµ„æºæ•´ç† « ⊹⊱⋛⋋ISong榮耀ζ組織™⋋⋛⊱⊹
Pingback: Favorites from the Feeds #01
Just what i was looking for! Thanks!
This is great! I love how Facebook implements this, and I’d be excited to try it on my blog.
Hey Ashley,
thanks for the tuto! Just a small note: the css file is missing in the zip download.
Dan
This is one of the best jquery tutorials I have seen recently. Added to http://tutlist.com
can also be used for posts?
Pingback: CSS Brigit | jQuery Ajax delete
This may be similar to other Ajax tutorials I’ve seen, but it’s definitely one of the most streamlined and easy-to-follow tutorials on the subject.
Pingback: News jQuery Ajax delete | Papermashup.com | Web 2.0 Designer
Cool. Looks similar to David Walsh’s inline delete thing
Designer and web developer, Co-founder and Technical Director at Harkable.com London. Previously I worked at InMobi, Spotify and MySpace. Interests include photography and making short videos. Also an avid F1 fan. I also run Mega Infographics for your daily dose of the best infographics.
Follow us on Twitter and get in-stream updates.
Subscribe to all the Papermashup tutorials and articles straight to your RSS reader.
Sign up and get all the Papermashup tutorials straight to your inbox.
79 discussions around jQuery Ajax delete