Solution:
You need to use the wp_ajax_
hook: https://developer.wordpress.org/reference/hooks/wp_ajax_action/
Simple example below:
You PHP code to process the ajax request:
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
// code that captures your ajax POST request
wp_die(); // this is required to terminate immediately and return a proper response
}
Your Ajax call:
jQuery('#favorite_user_post').submit(function (e) {
e.preventDefault();
var form = jQuery(this);
// note the added "my_action" to tell the server what function to fire (my be a better way to append this to your form data)
var url = form.attr('action') + "&=my_action";
jQuery.ajax({
type: 'POST',
url: url,
data: form.serialize(),
success: function (data) {
console.log(data);
},
error: function () {
console.log('Fail');
},
});
});