jQuery Ajax delete

17 July 2009| 45 Comments| Print

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.

jquery-delete

The Code

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();

jquery-delete1

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.

demodownload

45 Comments

  • Ben

    Cool. Looks similar to David Walsh’s inline delete thing

  • News jQuery Ajax delete | Papermashup.com | Web 2.0 Designer

    [...] See the rest here: jQuery Ajax delete | Papermashup.com [...]

  • Ashley (author)

    @ben can’t say i’ve seen it. could you post a link?

  • Jake Rocheleau

    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.

  • Ashley (author)

    @jake thanks for comment and I’m glad you found it useful! :)

  • CSS Brigit | jQuery Ajax delete

    jQuery Ajax delete…

    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.

  • dottorgonzo

    can also be used for posts?

  • Ashley (author)

    @dottorgonzo You could use if for any purpose to remove content from your database.

  • JDStraughan

    This is one of the best jquery tutorials I have seen recently. Added to http://tutlist.com

  • Daniel

    Hey Ashley,

    thanks for the tuto! Just a small note: the css file is missing in the zip download.

    Dan

  • Ashley (author)

    @Daniel thanks for that I’ve updated it the download :)

  • Inside the Webb

    This is great! I love how Facebook implements this, and I’d be excited to try it on my blog.

  • Dave

    Just what i was looking for! Thanks!

  • Favorites from the Feeds #01

    [...] 11. jQuery Ajax Delete [...]

  • 资源整理 « ⊹⊱⋛⋋ISong榮耀ζ組織™⋋⋛⊱⊹

    [...] 11. jQuery Ajax Delete [...]

  • Favorites from the Feeds #01 - Programming Blog

    [...] 11. jQuery Ajax Delete [...]

  • 網站製作學習誌 » [Web] 連結分享

    [...] jQuery Ajax delete [...]

  • ile

    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

  • 10+ JQuery tutorials for working with HTML forms

    [...] Lots of tutorials tells you how to add content using Ajax, but finding great info about deleting content isn't that easy. In this tutorial, you'll learn how to remove content using JQuery, for a similar result than in WOrdPress dashboard, when you validate a comment in the "Pending" section. Read tutorial [...]

  • 11 JQuery tutorials for working with HTML forms | Webmaster 9

    [...] jQuery Ajax Delete [...]

  • Twitted by jQueryLinks

    [...] This post was Twitted by jQueryLinks [...]

  • CoryMathews.com » 12 Slick jQuery Plugins

    [...] jQuery Ajax delete Plugin Page [...]

  • jQuery Ajax delete | Papermashup.com

    [...] post: jQuery Ajax delete | Papermashup.com Share and [...]

  • reki

    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

  • Ashley (author)

    @Reki thanks for the kind words, let me know what problems your having and i can point you in the right direction. ;)

  • reki

    thanks for responding. I actually figured it out, but thanks anyway Keep up the educational goodness

  • Martin

    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

  • Martin

    sorry, error in the above:

    <a href="#" id=" ” class=”delete”>

  • Martin

    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

  • Ashley (author)

    @martin thanks for the useful comments, do you want to email me your updated code so i can amend my post to let everyone know your updates? if so my email address is ashley [at] dotdashcreate [dot] com

    Thanks

    Ashley

  • Brad

    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.

  • James

    @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.

  • Matthew Fedak

    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!

  • Ashley (author)

    @Matthew glad you found it useful! thanks for the feedback ;)

  • 10 plugins exceptionnels pour jQuery « Armel Pingault

    [...] 3. Ajax delete [...]

  • sam s

    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.

  • Ashley (author)

    @sam, thats odd can you zip up your files and email them to me ashley at dotdashcreate dot com? i can take a look for you.

  • Thomas

    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

  • wHiTeHaT

    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

  • 30 Fresh AJAX Tutorials And Techniques - Noupe

    [...] can be frustrating. A fix for this problem would be to use MooTools and AJAX to do the loading.jQuery AJAX delete Being able to remove content with Ajax is useful for any Web designer. Using a few lines of jQuery, [...]

  • 30 Fresh AJAX Tutorials And Techniques – FreshTuts Tutorials, Resources, Web Trends, Code Snippets, Php scripts, Opensource, Ecommerce, Cms, Html, Xhtml scripts, Themes, Templates, Css design, Psd tuts, Photoshop, cs3

    [...] jQuery AJAX delete Being able to remove content with Ajax is useful for any Web designer. Using a few lines of jQuery, you can remove both a DIV and a record from the database with AJAX. In this demo, you’ll see a small red cross to the right of each comment. Clicking the cross will remove the comment’s DIV, and the slide-up animation allows you to remove the DIV. View the demo. [...]

  • 29 Fresh, Creative AJAX Tutorials And Techniques | Seventy Seven

    [...] jQuery AJAX delete Being able to remove content with Ajax is useful for any Web designer. Using a few lines of jQuery, you can remove both a DIV and a record from the database with AJAX. In this demo, you’ll see a small red cross to the right of each comment. Clicking the cross will remove the comment’s DIV, and the slide-up animation allows you to remove the DIV. View the demo. [...]

  • 30 Fresh AJAX Tutorials And Techniques » Shai Perednik.com

    [...] jQuery AJAX delete Being able to remove content with Ajax is useful for any Web designer. Using a few lines of jQuery, you can remove both a DIV and a record from the database with AJAX. In this demo, you’ll see a small red cross to the right of each comment. Clicking the cross will remove the comment’s DIV, and the slide-up animation allows you to remove the DIV. View the demo. [...]

  • Derleth

    gracias mi rey te amoooooooooooo
    :D

  • Derleth

    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

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.