0

I run into a problem, and I appreciate if anyone can help me resolve this.

Basically, I am making a code which allow user to add post to favorites, and save the favorite in cookie to remember it, but it fails. Here is my codes:

First, I use this code to run a function which check if user saved post or not:

<?php dt_fav_action(); ?>

And here is my dt_fav_action function:

function dt_fav_action() {
    global $post;
    $cookie = $_COOKIE['fav-'.$post->ID];
    if ($cookie == 1) {
        $user_faved = true;
    }
    if ($user_faved == true) {
        echo '<a href="';dt_favorites_link();echo '" class="faved">';dt_count_fav();echo '</a>';
    } else {
        echo '<a href="" class="addfav">';dt_count_fav();echo '</a>';
    }
}

And here is the $.ajax request which sends data to my php file to process the favorite and store the cookie etc.

$('.addfav').click(function(event){
    $(this).unbind('click');
    var parentfav = $(this).parent();
    var postid = $(this).parent().parent().parent().attr('id').replace(/[^0-9]/g, '');
    $(this).fadeOut();
    $.ajax({
        url: '<?php bloginfo('template_directory'); ?>/ajax/favorite.php',
        type: 'get',
        data: { postid : postid },
        dataType: 'json',
        success: function(data){
            parentfav.html('<a href="<?php dt_favorites_link(); ?>" class="faved">' + data.msg + '</a>');
            parentfav.children('.faved').css({'background-position' : 'left bottom', 'color' : '#1871a4'});
        }
    });
    return false;
});

And finally this is the favorite.php where I update the favorites count, and add cookie so it can be retrieved later via dt_fav_action function but here is the real problem, the $_COOKIE always returned null, it is not saved.

<?php

// include WordPress
require('../../../../wp-blog-header.php');
$data = array();

    // update post favorites count
    $postid = $_GET['postid'];
    update_post_meta($postid, 'faves', (int)get_post_meta($postid, 'faves', true)+1);
    $updated = get_post_meta($postid, 'faves', true);


    setcookie('fav-'.$postid, '1', time() + (20 * 365 * 24 * 60 * 60));

    $data['msg'] = $updated;

echo json_encode($data);

?>

setcookie part, I set the cookie when this is called via $.ajax and the script does not recognize any cookie after that, there fore it always fail and never remember the save state.

Please help .. I appreciate it in advance

Ahmed Fouad
  • 2,963
  • 10
  • 30
  • 54
  • Have you checked this question out? http://stackoverflow.com/questions/3431906/setting-a-cookie-in-an-ajax-request – Arne Jul 14 '12 at 11:35

1 Answers1

1

Set cookie to be available on all child directories of the root directory.

setcookie(
      'fav-'.$postid, 
      '1', 
      time() + (20 * 365 * 24 * 60 * 60), 
      "/"
);