So, I have been struggling with making ajax work. Here is my previous question: AJAX (admin_url('admin-ajax.php');?action=) Not Found
Anyway, I decided to narrow down and only have necessary files.
Here is the set up.
test.php
<div class="test">
<a href="#test_demo" id="demo">Items</a>
</div>
<div id="test_demo"> </div>
<script>
jQuery(document).ready(function() {
jQuery('.test a').click(function(e) {
e.preventDefault();
var tab_id = jQuery('this').attr('id');
jQuery.ajax({
type: "GET",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
dataType: 'html',
data: ({ action: 'test_tab', id: tab_id}),
success: function(data){
jQuery('#test_' + tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
</script>
function.php
function test_tab_callback() {
$template_part_path = 'page-parts/test_' . $_GET['id'];
get_template_part($template_part_path);
exit;
}
add_action('wp_ajax_test_tab', 'test_tab_callback');
add_action('wp_ajax_nopriv_test_tab', 'test_tab_callback');
test_demo.php
<div id="test_demo_content">Demo Content</div>
Here is the my idea on how it should work.
- test.php: When user clicks
Items
button, then thetab_id
variable in the jQuery saves the anchorid
(in this case, it will beid="demo"
). - Then admin-ajax.php is called.
- The saved id ("demo") is then passed onto the function.php and it is used in the variable
$template_part_path = 'page-parts/test_' . $_GET['id'];
which givespage-parts/test_demo
fortest_demo.php
Then the template part is called and calledback to the jQuery.
Then the data is "insert" into the
jQuery('#test_' + tab_id).html(data);
which isid="test_demo
.- The test_demo.php content should be displayed in the
#test_demo
div.
But it is not working. I used console.log(data)
but showed no result.
What am I doing wrong?