Passing element value to Ajax using JQuery

I am trying to pass the value from an anchor tag into ajax.

This is my HTML

Read More
<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(); // 
}

Related posts

Leave a Reply

3 comments

  1. You should use this to target the element which was clicked. This way, you only get the value of the attribute value, whose element was clicked upon.

    var value = $(this).attr('value');
    
  2. try like this

    jQuery(function($){
            $('.section').click(function () {
                var value = $(this).attr('value');
                jQuery.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {'action':'ajax_action','type':'post','post_id': value },
                    success:function(data) {
                        console.log(data);
                    },
                    error: function(errorThrown){
                        console.log(errorThrown);
                    }
                });     
            });  
        });