duanjiushu5063 2018-09-20 17:19
浏览 100

用AJAX调用的PHP函数不起作用

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);
}
  • 写回答

1条回答 默认 最新

  • doubi7496 2018-09-20 17:29
    关注

    Maybe too simple, but much forgotten; dit you use 'session_start()' in the PHP file? (To initiate the session manager)

    Also, always first check if $_SESSION['favorites'] is available and an array with:

    if(isset($_SESSION['favorites']) && is_array($_SESSION['favorites'])){
        array_push($_SESSION['favorites'], $post_id);
    }
    

    To avoid errors, it's easier to handle it directly instead of after the fix.

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)