Papermashup

Subscribe


Tweets


"RT @kycutwilson: @ashleyford @burgerbeartom incredible. There's 5 more left! Shout about it!!"

@ashleyford 3 days ago

"@burgerbeartom @kycutwilson finally got around to using my free burgers for life! And we weren't disappointed. http://t.co/nJ6p2nLtg4"

@ashleyford 2 weeks ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

jQuery Ajax delete

AshleyAshley

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

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 81
  • Happy Chhor Lyheang
    Posted on

    Happy Chhor Lyheang Happy Chhor Lyheang

    Reply Author

    Hello ! How can i delete with user session ?


  • sandy
    Posted on

    sandy sandy

    Reply Author

    $.ajax can also be use in recursion?
    and how to do it


  • Валентин
    Posted on

    Валентин Валентин

    Reply Author

    Спасибо.
    Very nice. You good programmer!
    Valentin from Ukraine.


  • Kabir
    Posted on

    Kabir Kabir

    Reply Author

    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


  • Andy
    Posted on

    Andy Andy

    Reply Author

    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


  • amit
    Posted on

    amit amit

    Reply Author

    James you are right it work with $_GET and $_REQUEST.
    Thanks for helping me.


  • Free Classifieds Ads
    Posted on

    Free Classifieds Ads Free Classifieds Ads

    Reply Author

    very nice script.it solve my problem.
    Thank :)


  • rouhollah
    Posted on

    rouhollah rouhollah

    Reply Author

    Hi.
    Is it possible to add a confirmation alert to this?

    Thanks.


  • john
    Posted on

    john john

    Reply Author

    wow :)
    Nice jquery script


  • Methemer
    Posted on

    Methemer Methemer

    Reply Author

    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 :)


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Methemer thanks for the heads up about the special characters should be all fixed now :)

      Ashley


  • Rach
    Posted on

    Rach Rach

    Reply Author

    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.


  • Mind Bird Solutions
    Posted on

    Mind Bird Solutions Mind Bird Solutions

    Reply Author

    Nice Job!!!!


  • Daniel van Flymen
    Posted on

    Daniel van Flymen Daniel van Flymen

    Reply Author

    Bravo!


  • web design
    Posted on

    web design web design

    Reply Author

    wow..this is the most amazing steps to get the hand dirty….thanks for sharing this….


  • Brent
    Posted on

    Brent Brent

    Reply Author

    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?


  • Brent
    Posted on

    Brent Brent

    Reply Author

    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.


  • Marcus
    Posted on

    Marcus Marcus

    Reply Author

    how to use more variables?


  • Rodrigo
    Posted on

    Rodrigo Rodrigo

    Reply Author

    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.


  • Adam
    Posted on

    Adam Adam

    Reply Author

    Great tutorial, but I did notice the class “clear” was never added into the css.

    div.clear {
    clear: both;
    }


  • Virtulian
    Posted on

    Virtulian Virtulian

    Reply Author

    Hi
    I am new in jquery so thank you for that as it helps me lot.

    Regards


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @ Virtulian,

      Glad you found it helpful thanks for passing by :)

      Ashley


  • pols
    Posted on

    pols pols

    Reply Author

    thanks to this tutorial.. It’s works fine..


  • Nele
    Posted on

    Nele Nele

    Reply Author

    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?


  • Aji Prabowo
    Posted on

    Aji Prabowo Aji Prabowo

    Reply Author

    Nice share, just fine tuned it a bit,. and wala,,.. it just works like a charm. Thanks. two thumbs up.


  • Nauman Akhtar
    Posted on

    Nauman Akhtar Nauman Akhtar

    Reply Author

    this is good, but seems to be slow, isn’t it so?


  • Ryan Woodard
    Posted on

    Ryan Woodard Ryan Woodard

    Reply Author

    Great tutorial! i cant seem to get the download to work?


  • Derleth
    Posted on

    Derleth Derleth

    Reply Author

    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


  • Derleth
    Posted on

    Derleth Derleth

    Reply Author

    gracias mi rey te amoooooooooooo
    😀


  • wHiTeHaT
    Posted on

    wHiTeHaT wHiTeHaT

    Reply Author

    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


  • Thomas
    Posted on

    Thomas Thomas

    Reply Author

    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


  • sam s
    Posted on

    sam s sam s

    Reply Author

    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
      Posted on

      Ashley Ashley

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


  • Matthew Fedak
    Posted on

    Matthew Fedak Matthew Fedak

    Reply Author

    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
      Posted on

      Ashley Ashley

      Reply Author

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


  • James
    Posted on

    James James

    Reply Author

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


  • Brad
    Posted on

    Brad Brad

    Reply Author

    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.


  • Martin
    Posted on

    Martin Martin

    Reply Author

    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
      Posted on

      Ashley Ashley

      Reply 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


  • Martin
    Posted on

    Martin Martin

    Reply Author

    sorry, error in the above:

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


  • Martin
    Posted on

    Martin Martin

    Reply Author

    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


  • reki
    Posted on

    reki reki

    Reply Author

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


  • reki
    Posted on

    reki reki

    Reply Author

    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
      Posted on

      Ashley Ashley

      Reply Author

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


  • ile
    Posted on

    ile ile

    Reply Author

    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


  • Dave
    Posted on

    Dave Dave

    Reply Author

    Just what i was looking for! Thanks!


  • Inside the Webb
    Posted on

    Inside the Webb Inside the Webb

    Reply Author

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


  • Daniel
    Posted on

    Daniel Daniel

    Reply Author

    Hey Ashley,

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

    Dan


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

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


  • JDStraughan
    Posted on

    JDStraughan JDStraughan

    Reply Author

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


  • dottorgonzo
    Posted on

    dottorgonzo dottorgonzo

    Reply Author

    can also be used for posts?


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

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


  • Jake Rocheleau
    Posted on

    Jake Rocheleau Jake Rocheleau

    Reply Author

    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
      Posted on

      Ashley Ashley

      Reply Author

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


  • Ben
    Posted on

    Ben Ben

    Reply Author

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


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

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