0

I'm getting trying to learn some AJAX for WordPress yet getting stumped at what seems like it should be simple. AJAX function gets the ID correctly, sends it via admin-ajax.php (which I can see in XHR tab of devtools) but function won't receive it. What am I missing please?

jQuery(document).ready( function($) {

    var post_id = $('article').attr('ID');
    post_id = post_id.replace('post-','');
    console.log(post_id);

    $.ajax({
        url: updatecount.ajax_url,
        data : {
            action : 'updateCount',
            post_id : post_id,
        },

        success : function( data ) {
           console.log(data)
        },

        error : function( data ) {
            console.log('failed');
        }

    })
})

...and the function it is calling is as follows:

function updateCount() {

    $post_id = intval($_POST['post_id']);
    echo 'Function has ID as: '. $post_id;
    die(); 
}

This returns the following console output:

AJAX has ID as: 187963
Function has ID as: 0
1
  • maybe it is a reserved term. It is not listed, but post_id sounds like a old wp fallback. Commented Dec 12, 2017 at 19:07

1 Answer 1

1

By default, jQuery.ajax makes GET requests, but you're checking for data in $_POST. You'll either want to check $_GET on the PHP side, or add method: 'POST' to your jQuery.ajax options object.

Note that if you're using a very old jQuery (pre 1.9.0) you'll need to use type: 'POST' instead of method: 'POST', per the docs on the options object.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Joel that was the issue, using $_POST instead of $_GET. All working as expected now, nice one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.