phpajaxwordpresspostjquery-ajax

Can not pass variable from jquery to php


I want to pass a variable from jquery to PHP on the same page (I am using WordPress).

I tried using using ajax post like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
        $("li.year-item a").click(function(){
            $post = $(this);
            $.ajax({
                type  : "POST",
                url: "https://example.com/exhibition/",
                data: {yearValue: $($post).attr("value")},
                success: function (data) {
                    console.log(data);
                }
            })
        });
    });
</script>

and I get the post variable below the script tag:

<?php var_dump($_POST['yearValue']); ?>

but the var_dump result is null..

I have no idea.. anyone can help me? thanks in advance :)


Solution

  • In Wordpress you should use the built in Ajax mechanism.

    $.ajax({
        type  : "POST",
        url: "https://your-site.com/wp-admin/admin-ajax.php",
        data: {
            action: 'retrieve_yearvalue', 
            yearValue: $($post).attr("value"),
            test: 'Test is ok'
        },
        success: function (data) {
            console.log(data);
        }
    })
    

    On PHP-Side:

    add_action( 'wp_ajax_retrieve_yearvalue', 'my_year_retrieve_function' );
    add_action( 'wp_ajax_nopriv_retrieve_yearvalue', 'my_year_retrieve_function' );
    
    function my_year_retrieve_function() {
        $yearValue = $_REQUEST['yearValue'];
        $test = $_REQUEST['test'];
        
        $response = array(
            'recieved_year' => $yearValue,
            'test_data' => $test
        );
        
        wp_send_json( $response );
    }