Asesha George Asesha George - 7 months ago 32
Javascript Question

How to close Bootstrap collaps after AJAX success

I am using a Bootstrap collapse control in my webpage. Whenever I click on the link it used to open and close. I am using AJAX to send data to a PHP page and on success print the result. After the AJAX call

data-toggle
should close. Please see my code below.

<a data-toggle="collapse" href="#review" class="open-code btn btn-default">Write a Review</a>
<div id="review" class="collapse code">
<form id="review">
my code...
</from>
</div>


$(function() {
$(document).on('submit', '#review_post', function(e) {
//var $this = $(this);
var message = $(this).find("#message").val();
var rating = $(this).find("#input-2c").val();
var vendor_id = $(this).find("#vendor_id").val();
var infostring = 'message=' + message + '&rating=' + rating + '&vendor_id=' + vendor_id;

if(message=='') {
alert('Please add your Message');
} else {
$.ajax({
type: "POST",
url: "/review_vendor.php",
data: infostring,
success: function(data){
//alert(data);
$('#review_post').each(function() {
this.reset();
});
// here I want to use the code to close data-toggle

$("#flash").append(data);
}
});
}
e.preventDefault();
});
});


I tried this code but it's not working:

$(this).find('.collapse').trigger('click');

Answer

You should call the collapse() method on the a element again, providing 'hide' as the argument. Try this:

$(this).find('.collapse').prev('a').collapse('hide');

Collapse documentation

Also note that you can make several small adjustments to your code to make it follow best practices. Here's a full example:

$(document).on('submit', '#review_post', function(e) {
    e.preventDefault();  
    var $this = $(this);
    var message = $this.find("#message").val();
    var rating = $this.find("#input-2c").val();
    var vendor_id = $this.find("#vendor_id").val();

    if (message == '') {
        alert('Please add your Message');
    } else {
        $.ajax({
            type: "POST",
            url: "/review_vendor.php",
            data: {
                message: message,
                rating: rating,
                vendor_id: vendor_id                    
            },
            success: function(data) {
                $('#review_post').each(function() {
                    this.reset();
                }); 
                $this.find('.collapse').prev('a').collapse('hide');
                $("#flash").append(data);
            }
        });
    }
}); 
Comments