I am attempting to save favorites to a session by clicking on a button. I'm using AJAX to call the php function save_favorite(). The function is being called but for some reason the save_favorite_in_session_variable() method just won't work when being called like this. I've tested the function by itself and it works fine. Does anyone have a clue what I'm missing?
//JavaScript
$(document).on('click', '.add-favorite', function() {
var imgId = $(this).data('id');
saveFavorite(imgId);
});
function saveFavorite(imgId) {
var data = {
'action': 'save_favorite',
'id' : imgId
};
jQuery.post(my_ajax_object.ajax_url, data, function(response) {
alert(response);
});
}
// PHP
function save_favorite() {
ob_start();
debug_to_console('saving favorite');
if ($_POST['id']) {
$post_id = $_POST['id'];
save_favorite_in_session_variable($post_id);
}
wp_die();
}
add_action('wp_ajax_save_favorite', 'save_favorite');
add_action('wp_ajax_nopriv_save_favorite', 'save_favorite');
function save_favorite_in_session_variable($post_id) {
array_push($_SESSION['favorites'], $post_id);
}