bɪˈɡɪnə
bɪˈɡɪnə

Reputation: 1085

How do I toggle content between tabs through ajax/php?

I have divided my content in two tabs and switching between two tabs with javascript.

<div class='tab-container'>
<div class='tab-1'>
<?php 
$sql="SELECT * FROM posts WHERE status='tab1'";
echo "<div class='db'
<h2>post</h2></div>";
?>
</div>
<div class='tab-2'>
<?php
$sql="SELECT * FROM posts WHERE status='tab2'";
echo "<div class='db'
<h2>post</h2></div>";
?>
</div>
</div>   

Php code divides content between tabs through WHERE clause select * from posts where status='tab1'; so to remove post from one tab ajax request given below triggers php code which updates status of content from tab1 to tab2.

<script type="text/javascript">
$(function() {
$(".restore").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Restore?"))
  {
$.ajax({
type: "GET",
url: "restore.php",
data: info,
success: function(){ 
}
});
     $(this).parents(".db").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>

So that post is removed from tab1. Idea here is to move post from one tab to another through ajax. javascript works good on removing post from one tab however for making that post appear in another tab I have to reload page as I haven't used ajax for that. So problem is I don't get how to add that post dynamically to another tab through ajax without refreshing page.

Upvotes: 2

Views: 1842

Answers (4)

user1562300
user1562300

Reputation:

Agree with @Niranjan N Raju. But want to add some addition.

Use console.log(data) instead alert(data) as last don't shows object info.

Upvotes: 1

AldoZumaran
AldoZumaran

Reputation: 572

Try this

HTML

<div class="tabs" id="d-tab1"></div>
<div class="tabs" id="d-tab2"></div>
<a href="#" class="restore"  id="tab1">
<a href="#" class="restore"  id="tab2"> 

JS

$('.restore').click(function(e){
    e.preventDefault();
    var $tab = $(this);
    $.post('restore.php',{id: $tab.attr('id')},function(html){
        $('.tabs').hide();
        $('#d-'+$tab.attr('id')).html(html).show();
    })
})

Or use Jquery tabs https://jqueryui.com/tabs/

Upvotes: 1

Rahul Date
Rahul Date

Reputation: 11

In restore.php, you should get the selected post and then then update the status of that post to tab2. And append that result in main php page. You can append the same via restore.php.

Upvotes: 1

Niranjan N Raju
Niranjan N Raju

Reputation: 11987

To get content from ajax call, you have to echo it in server side.

May be something like this

echo "hi, this is new content";

Now in ajax success

success: function(data){  
     alert(data); this will alert what was echoed in php(hi, this is new content)
}

If you want to add the content to some div in view,

$("class or id for the div").html(data);

Upvotes: 1

Related Questions