Reputation: 257
I have a page which displays content in boxes. Above these boxes are four buttons, when clicked they filter the content below it. The first time I press any of the buttons the filter works great, however if I press the button for a second time then it doesn't work.
I am only replacing the filtered content div (the boxes), so the buttons used to filter aren't being replaced. I'm assuming some kind of binding/linking issue but haven't been able to get to the bottom of it.
Any help appreciated.
My view (the console.log in my click function always displays the correct button ID):
$(document).ready(function () {
jQuery('.btnSubmit').on('click', function(e){
e.preventDefault();
var mypage_id = this.id;
console.log(mypage_id);
var url = "http://localhost/site/get_list_view";
$.ajax({
url: url,
type: 'POST',
data: { my_data: this.id},
cache: false,
success : function(data){
if(data){
$('.deals').replaceWith(data);
}
}
});
});});
My controller (reduced it to just echo my data, and creates a random number every time it's hit - the data and the number never changes after that first hit):
public function get_list_view(){
$my_data = $this->input->post('my_data');
echo($my_data);
echo(rand(10,100));}
Any tips?
Cheers
Upvotes: 0
Views: 1037
Reputation: 2383
I would say its because after you run this line:
$('.deals').replaceWith(data);
the html element with the class ".deals" is totally replaced with your ajax response. If your ajax response doesn't have a containing element with the ".deals" class it will never work again until you refresh the page.
Also you could simply rewrite that line to say:
$('.deals').html(data);
and then your response doesn't need to have a ".deals" wrapping class element as you're no longer replacing but filling it with the response.
Without all your code the above is my best guess. Another guess is that sometimes jquery event handlers do not reattache properly after an ajax refresh of content, in the old days we used "live" to handle that, but its been replaced with a new usage of .on:
$( document ).on( events, selector, data, handler );
So in your case that would look like:
jQuery(document).on('click', '.btnSubmit', function(e) {
... rest of your code
Upvotes: 3