I am using a button to post data using ajax (Join and leave a group like facebook), after post is successful it will refresh part of the page element and and reload the content. Once the content is reloaded it will replace the button as well.
<div id = "#profile-pic">
.....
<a class="btn button_intro join_leave_group" href="#">Join Group</a>
.....
</div>
After the div is reloaded button changes to
<div id = "#profile-pic">
.....
<a class="btn button_intro join_leave_group" href="#">Leave Group</a>
.....
</div>
The problem is when I click "Join Group" button it will Join group, refresh the div element and replace the button to "Leave Group" (it takes longer time to receive response) but if I click in the leave group it doesn't trigger the button click. but if refresh the page and click Leave Group button it works fine but then again Join Group doesn't work.
Here is my script:
<script>
$( document ).ready(function() {
$('.join_leave_group').click(function(){
var type = $('.join_leave_group').text();
if(type == "Join Group"){
var xhr = null;
console.log("I was clicked"); //test if clicked
var xhr = $.ajax({
type: 'POST',
url: '/join',
data: {
group: "{{ some value }}"
},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
if(xhr != null) {
xhr.abort();
}
},
success: function (data){
$('#profile-pic').load(document.URL + ' #profile-pic');
xhr.abort();
}
});
}else{
console.log("I was clicked"); //test if clicked
var xhr = null;
var xhr = $.ajax({
type: 'POST',
url: '/leave',
data: {
group: "{{ some value }}"
},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
if(xhr != null) {
xhr.abort();
}
},
success: function (data){
$('#profile-pic').load(document.URL + ' #profile-pic');
xhr.abort();
}
});
}
});
});
</script>
Anyone can help on this, or explain why its happening? or what will be the best option to create a Join/Leave button like facebook groups.
Thanks in advance, for taking your time to check on this.