As for your PHP not being executed – the action
parameter in your JavaScript AJAX call needs to match the hook name in your add_action
call. Take a look at the example below. I haven’t tested it but it should work. I have simplifed the AJAX call, feel free to modify it to suit your use case.
var data = {
action: 'jk-author-follow', // Look Ma' I talk to your PHP! :)
// ...
// here you can add any other custom vars you need to pass to the PHP handler
};
$.post(ajax_var.url, data, function(response){
if( typeof(console) == 'object' ) console.log( response );
});
Another thing to keep in mind is a context in which the PHP function is executed. It runs as a separate request and therefore it’s not aware of the current loop etc. You might need to pass additional variables (i.e. user_id
) in your data
object.
As a side note – the nopriv
variant of the hook runs for the users who are not logged in. If you intend your functionality exclusively for the logged-in users you might as well drop it.
There’s a lot of useful info in the Highest Voted ‘ajax’ Questions here on WPSE. You can also take a look at my older answer to a related question: Adding callback function for wp_ajax_ has no effect. Most of the information mentioned there will be relevant for you as well.