how to built ajax tabs in wordpress? - php

I try to display the departments in my website as tabs, when click one tab it will display the data related to this department according to department_id.
I try this code Execute php function only when clicked (wordpress) but I need the tabs number to be dynamic.
<div class="tabs">
<ul>
<?php
$arr1=array(2,3,5,10,22,25,27,28,29,30);
$arr2=array("dep1","dep2","dep3","dep4",
"dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++){?>
<li><a href="#tab" id="<?php echo $arr1[$i]; ?>"><?php echo
$arr2[$i];?>
</a></li>
<?php } ?>
</ul>
</div>
<div id="tab" class="section">
</div>
functions.php:
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here I print data according to $dept_id **/
die();
}
?>
script.js:
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab').html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });
it dose not work, it displays data only for one tab.
console.log(tab_id) ----> it display the id for the first tab clicked
and did not change when click another tab.

You need to echo the output from the tabsfunction and also add the die() at end of the function like below :
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here display data according to $dept_id **/
echo 'output';
die();
}
Hope it helps.

can you please correct your tab list code.
<div class="tabs">
<ul>
<?php
$arr1 = array(2,3,5,10,22,25,27,28,29,30);
$arr2 = array("dep1","dep2","dep3","dep4","dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++)
{
?>
<li><?php echo $arr2[$i];?></li>
<?php
}
?>
</ul>
</div>
<?php for($i=0;$i<10;$i++)
{
?>
<div id="tab<?php echo $arr1[$i]; ?>" class="section">
</div>
<?php
}
?>
Also return proper response on ajax request.
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id = $_GET[id];
echo $dept_id; // this just dispay requsted id as tab content here you can add your logic for dynamic content based on id
die();
}
?>
And your script js look like this
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });

Related

POST in AJAX dont work when i redirect to the page

Hello im struggling with my Code :
I try to post some data to a php page :
$('.choixvol').click(function() {
var id = "testid";
$.ajax({
type: 'POST',
url: 'vol.php',
data: {
id: id
},
success: function() {
window.location.href = "vol.php";
},
});
});
But when I redirect to my PHP page the isset() doesn't work :
vol.php :
<?php
require'header_fr.php';
logged_only();
if(isset($_POST['id'])){
$id = $_POST['id'];
}else{
$id = "not isset";
}
?>
<div id="container"class="container">
<div class="form-wrap text-center">
<?php echo $id ?>
</div>
</div>
<?php
require'footer_fr.php';
?>
And display "not isset"
If you want to get the id when you redirect to the page, pass it in via GET method (providing the id is not private and is ok to be viewed in the url).
$('.choixvol').click(function() {
var id = "testid";
$.ajax({
type: 'POST',
url: 'vol.php',
data: {id: id},
success: function() {
window.location.href = "vol.php?id=" . $id;
},
});
});
<?php
require'header_fr.php';
logged_only();
if(isset($_POST['id'])){
//Do something with your post ID when using the post method
}
if(isset($_GET['id'])){
//Do something with your GET ID when redirected back with the GET method
$id = $_GET['id'];
}
?>
<div id="container"class="container">
<div class="form-wrap text-center">
<?php echo $id ?>
</div>
</div>
<?php
require'footer_fr.php';
?>
Although the comments on the OP are correct, this method is nonsense.

refresh an included page

I have a page index.php
Inside of it is a friendlist that updates the db with a button click without refreshing the page. Now I want that only the friendlist refreshs so its updated
<html>
<body>
<?php
include ("friendlist.php");
?>
</body>
</html>
friendlist.php:
<script>
function adduser() {
var data=$("#adduserform").serialize();
$.ajax({
type: "POST",
url: "addfriend.php",
data: data,
dataType: "html",
success: function(data)
{
//refresh myFriendlist or requser so its updated
}
});
}
</script>
<div id="myFriendlist" class="friendlist-content">
<?php if(!empty($request)) { ?>
<div id="req">
<h2 id="reqh">Anfragen</h2>
<?php foreach($request as $row) {
$row['userAname'] = (strlen($row['userAname']) > 5) ? substr($row['userAname'], 0, 5) . '...' : $row['userAname'];
?>
<div id="requser">
<a class="reqimg" style="padding:0px;" href="user.php?id=<?php echo ($row['id']);?>">
<img class="reqpb" src="./users/<?php echo ($row['userAid']); ?>/pb.jpg" alt="Bild nicht gefunden" onerror="this.src='./img/no_pb.png';"></img>
</a>
<a class="reqnm" style="padding:0px;" href="user.php?id=<?php echo ($row['userAid']);?>"><?php echo $row['userAname']; ?></a>
<img id="aimg" src="./img/accepticon.png">
<form id="adduserform" name="adduserform">
<input type="hidden" id="reqid" name="reqid" value="<?php echo $row['userAid'];?>" />
<input type="hidden" id="reqnm" name="reqnm" value="<?php echo $row['userAname'];?>" />
</form>
<img id="aimg" src="./img/dntaccepticon.png">
</div>
<?php
}
?>
</div>
<?php
}
?>
</div>
How can I do that?
You can refresh an external file using ajax. For example, if you had a div with the id "friendslist" you could refresh its contents this way:
$.ajax({
url: "friendlist.php"
}).done(function(response) {
$( '#friendslist' ).html( response );
});
The documentation for ajax is on the jQuery site here: http://api.jquery.com/jquery.ajax/.
If you can make "addfriend.php" to return the new complete list of users, so that would be:
<?php foreach($request as $row) {
$row['userAname'] = (strlen($row['userAname']) > 5) ? substr($row['userAname'], 0, 5) . '...' : $row['userAname'];
?>
you could use that response, which you will receive when you do the AJAX call, to refresh the friendlist, using the jquery HTML function (http://api.jquery.com/html/)
you can follow this code but not tested
first update your index.php
<html>
<body>
<div id="friendlist">
<?php
include ("friendlist.php");
?>
</div>
</body>
</html>
then update your addfriend.php as like
<?php
// your code here
// then include your frindlist.php content
include 'yourpath/frindlist.php'
?>
then update your javascript code like this
function adduser() {
var data=$("#adduserform").serialize();
$.ajax({
type: "POST",
url: "addfriend.php",
data: data,
dataType: "html",
success: function(data)
{
$('#friendlist').html(data);
}
});
}

ajax a href onclick get php variable and execute php file

Before I ask this question, I have already referred to the example of this question. However, it seems doesn't work. Without using ajax, I can get my post deleted but after implement ajax, the deleteAtc.php seems to be not working.
My delete page code (delete.php)
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> Delete<br />
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = <?php echo $article['article_id']; ?>;
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id"+id+,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
<div id="success"></div><br />
<?php } ?>
While my deleteAtc.php code:
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
echo "Article deleted";
}
}
?>
What I'm trying to do here is to delete the record without redirect to deleteAtc.php, it will remove out the record and replace Article Deleted
May I know where did I go wrong in ajax side?
Please refer below for updated question
Based on the answer below, here is my updated code:
delete.php
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
deleteAtc.php
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
Somehow, if I delete two record at a time, only the first record echo the result, the second result deleted doesn't echo out the result.
Am wondering, possible to add jquery animation to .show the success message and .hide the record deleted?
First of all IDs are not meant to be duplicated, use class selector instead. Also you could make use of custom data attributes to store the id of the article.
Try
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
Script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
And in server side
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
The above script won't work you have to change like below. You are repeating the same identifier function again and again. Keep the jquery script out of foreach loop. You have to add the class property with the article id.
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> <a href="#" id="link" class='<?php echo $article['article_id']; ?>' >Delete</a><br />
<div id="success"></div><br />
<?php } ?>
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = $(this).prop('class');
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+id,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
You create several links with id="link". ID must be unique.
You have to write
id="link<? echo $article['article_id']; ?>"
as well as
$('#link<? echo $article["article_id"]; ?>').click(function() {...})
<script language="javascript">
$(document).ready(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this record? There is NO undo!"))
{
$.ajax({
type: "GET",
url: "products/delete_record.php",
data: info,
cache: false,
success: function(){
setTimeout(function() {
location.reload('');
}, 1000);
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
//location.reload();
});
});
</script>

Nivo Slider dose not load the Ajax response from PHP file

I'm trying import images to HTML using PHP, but NivoSlider not loaded that.
I looked for the cause of the problem.
I am printing a alert message of response and the right.
Here is the HTML and AJAX query:
<div id="workcontent" class="pcontent" style="display:none;">
<div class="slider-wrapper theme-default">
<div id="slider" class="nivoSlider">
</div>
</div>
<script>
$(document).ready(function() {
var wl = $('#worklist div');
wl.on('click', function(){
var name = $(this).attr('id');
console.log(name);
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response);
alert(response);
});
});
});
</script>
<div id="back"></div>
<div id="backcontainer">
<div id="back">
Back
</div>
</div><!--End backcontainer-->
</div><!--End content-->
And here is the other jQuery:
<script>
$(document).ready(function() {
$('#slider').nivoSlider(function(){alert('OK');});
});
</script>
This alert don't show! ):
Finally, here is the PHP code:
<?php
if (isset($_POST["data"])){
if ($_POST["data"] == "") {
echo "data ures";
} else {
$data = $_POST["data"];
$fname = "content/".$data."/*.*";
$files = glob($fname);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'" data-thumb="'.$num.'">';
}
}
} else {
echo "nem jott data";
}
?>
Sorry for my bad english
NivoSlider doesn't take a function as an argument.
Also .nivoSlider() is probably called before the AJAX call returns it's response.
A better solution would be:
$(document).ready(function() {
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response).nivoSlider( {} );
});
});
Now you can be fairly sure #slider contains the images from the response body so NivoSlider can act on them.

Jquery, ajax and problem with load

This is the HTML part:
div id="messages">
<div class="messages">
<?php if(isset ($unread)) { ?>
<p>You have <?php echo $unread?> unread messages.</p>
<?php } ?>
<?php if(isset ($messages)) { ?>
<?php foreach ($messages as $msg){ ?>
<div class="col_3">
<?php
if($msg['read'] == 0){ echo 'Status of message: Unreaded';}
elseif($msg['read'] == 1){echo 'Status of message: Readed';}
echo "<p>Message from: $msg[name]</p>";
echo "<p>Sender email: $msg[email]</p>";
echo "<p>Message: <br />$msg[message]</p>"; ?>
Delete message
</div>
<?php } ?>
<?php } ?><!-------- end of if $message-------->
</div><!------ end of div .messages--------->
</div><!------ end of div #messages--------->
and JQ:
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>");
});
});
}
});
return false;
});
Code is working, but when it comes to the load nothing is being shown. I did
load("<?php echo site_url('messages/show') ?>", function() {
alert('Load was performed.');
});
and there was an alert, and when I look page source I can see that the content has been changed, but it is not displayed.
When you view the source of a page that has been loaded via AJAX, it will never update. You will need to inspect the DOM in order to see what has changed.
The reason is because the content is not actually on the page and is being dynamically added to the page.

Categories