I am trying to pass the value from an anchor tag into ajax.
This is my HTML
<section>
<div class="nav-section">
<nav>
<ul>
<li><a href="#" class="section" value="news">News</a></li>
<li><a href="#" class="section" value="highlights">Highlights</a></li>
</ul>
</nav>
</div>
</section>
I use this script to retrieve, and send to ajax. This is where I run into trouble. I can alert the value, using alert(value)
, but when I pass it like so: post_id: value
, no data is send.
Script
jQuery(function($){
$('.section').click(function () {
var value = $('.section').attr('value');
jQuery.ajax({
url: ajaxurl,
data: {
'action':'ajax_action',
'type':'post',
'post_id': value
},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
});
When I var_dump
the id, I get a null value. The function is running but has no data.
When all of this is done i want to use the value to retrieve a get_template_part
in wordpress, and pass it in to the html.
AJAX in functions.php
function ajax_action_stuff() {
$post_id = $_POST['post_id'];
var_dump($post_id);
echo $post_id;
die(); //
}
You should use
this
to target the element which was clicked. This way, you only get the value of the attributevalue
, whose element was clicked upon.Try this
try like this