0

hi i am designing a real estate website and i have many ads in it i add an option to every of my ads and if user click on "add to favorites" that ad's id and url saves in a cookie and retrieve in "favorite page" thus user can review that certain ad every time he or she wants. each of my ads have a address like this localhost/viewmore.php?ID=a number
totally saving process in cookie works fine but recently i realized something. consider i visit one of my ads with this address localhost/viewmore.php?ID=10 and click on "add to favorite" then if i open another page with this address localhost/viewmore.php?ID=8 and then i read my cookie in "favorite page" i will see this result
[{"favoriteid":"10","url":"http://localhost/viewcookie.php?ID=10"},{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8"}]
which is perfectly true and it is what i expect.

the problem

now consider unlike the previous case i open both of ads and then click on "add to favorite" on first ad and then go to second ad (without any refreshing) and click on "add to favorite" on second ad this time if i read my cookie in "favorite page" i will see this result
[{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8"}]
which is not true i want two see both of ad's id and url in my cookie not just last one.
ps: i use push() method to add new object to cookie array i think i have to update it every time after click? any idea thanks

/*
  * Create cookie with name and value.
  * In your case the value will be a json array.
  */
  function createCookie(name, value, days) {
    var expires = '',
    date = new Date();
    if (days) {
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = '; expires=' + date.toGMTString();
    }
    document.cookie = name + '=' + value + expires + '; path=/';
  }
  /*
  * Read cookie by name.
  * In your case the return value will be a json array with list of pages saved.
  */
  function readCookie(name) {
    var nameEQ = name + '=',
    allCookies = document.cookie.split(';'),
    i,
    cookie;
    for (i = 0; i < allCookies.length; i += 1) {
      cookie = allCookies[i];
      while (cookie.charAt(0) === ' ') {
        cookie = cookie.substring(1, cookie.length);
      }
      if (cookie.indexOf(nameEQ) === 0) {
        return cookie.substring(nameEQ.length, cookie.length);
      }
    }
    return null;
  }
  function eraseCookie(name) {
    createCookie(name,"",-1);
}

    var faves = new Array();
   function isAlready(){
    var is = false;
    $.each(faves,function(index,value){
      if(this.url == window.location.href){
        console.log(index);
          faves.splice(index,1);
          is = true;
      }
    });
    return is;
  }
$(function(){
var url = window.location.href; // current page url
    var favID;
    var query = window.location.search.substring(1);

 var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        var favID = (pair[0]=='ID' ? pair[1] :1)
//alert(favID);
 }
// this is the part i think i have to update every time without refreshing*******************************
 $(document.body).on('click','#addTofav',function(e){
  e.preventDefault();
       if(isAlready()){
      } else {
          var fav = {'favoriteid':favID,'url':url};
          faves.push(fav);  
 }
//*******************************************************************************************************
 var stringified = JSON.stringify(faves);
    createCookie('favespages', stringified);
 });
  var myfaves = JSON.parse(readCookie('favespages'));
    if(myfaves){
    faves = myfaves;
    } else {
    faves = new Array();
    }

});
Malekian
  • 315
  • 8
  • 27
  • 2
    As Somerset Maugham said: "Kill you darlings." You have both a wall of text and a wall of code. A good 80% of the text is irrelevant to the problem at hand. That's probably true of the code as well. See: [*How do I ask a good question?*](/help/how-to-ask) and [mcve]. – T.J. Crowder Jul 15 '16 at 07:06
  • Have you checked SO for similar questions? http://stackoverflow.com/questions/23933443/sharing-cookie-among-browser-tabs-without-refreshing-tab – ExoticChimp Jul 15 '16 at 07:08
  • Also are you able to make use of localStorage rather than cookies? – ExoticChimp Jul 15 '16 at 07:09
  • @T.J. Crowder hi thank you for answering if you read my question you will see my question is a little complicate to explain thus i proposed my question very simple and of course it is a little long – Malekian Jul 15 '16 at 07:09
  • @ExoticChimp except this problem this code works fine and i do not want to start from first step again – Malekian Jul 15 '16 at 07:11
  • The question is complicated, but I very much doubt the actual problem is. See the second link above. – T.J. Crowder Jul 15 '16 at 07:13
  • People actually do this? Favorite ads? – Tibrogargan Jul 15 '16 at 07:16
  • @Tibrogargan it is a common option in most of the websites. with this option user can review his or her favorite ad every time without bothering himself to find that certain ad again – Malekian Jul 15 '16 at 07:20
  • I think even though you have wrote some code for storing the cookie, refactoring to use localStorage wouldn't exactly be difficult and would take 10-15 mins? You're going to have to refactor anyways because it doesn't work. Check my link above if you really do want to use cookies for this functionality – ExoticChimp Jul 15 '16 at 07:24
  • @user6362236 Oh, I think you mean your listings, as opposed to advertisements that may be coming from a 3rd party. Either way, why are you replicating a function that's already part of the browser? – Tibrogargan Jul 15 '16 at 07:24
  • @Tibrogargan I think he's trying to create a sort of "Wishlist" type functionality you see on sites like AirBnB and ecom sites – ExoticChimp Jul 15 '16 at 07:26
  • @Zeeshan hi man could u please take a look at this question it is look like this question `http://stackoverflow.com/questions/23933443/sharing-cookie-among-browser-tabs-without-refreshing-tab` which u asked some times ago but i could not unerstand the answer could u please help me – Malekian Jul 15 '16 at 12:29
  • Just a suggestion, but you should not use cookies for this. This is stuff that a user might want to see on more than one device. (see Zillow website and how it has a mobile app etc). If a user wants to save a property, it should be added to a shared profile, on a database or other remote service, so that they don't have to be on the same machine, they just sign in. – Nikki9696 Jul 15 '16 at 18:10
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/117521/room-for-malekian-and-slayther). – Božo Stojković Jul 17 '16 at 09:39

1 Answers1

0

Your problem is that you are looking at variable faves, which is initialized at document load, but it isn't being updated as cookie changes.

The second page looks at the variable, sees no favorites from first page, because it doesn't actually look at cookie.

Then, it just resets the cookie with it's values.

Here is the full code, with added functionality from chat:

/* 
 * Create cookie with name and value. 
 * In your case the value will be a json array. 
 */
function createCookie(name, value, days) {
  var expires = '',
    date = new Date();
  if (days) {
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = '; expires=' + date.toGMTString();
  }
  document.cookie = name + '=' + value + expires + '; path=/';
}
/* 
 * Read cookie by name. 
 * In your case the return value will be a json array with list of pages saved. 
 */
function readCookie(name) {
  var nameEQ = name + '=',
    allCookies = document.cookie.split(';'),
    i,
    cookie;
  for (i = 0; i < allCookies.length; i += 1) {
    cookie = allCookies[i];
    while (cookie.charAt(0) === ' ') {
      cookie = cookie.substring(1, cookie.length);
    }
    if (cookie.indexOf(nameEQ) === 0) {
      return cookie.substring(nameEQ.length, cookie.length);
    }
  }
  return null;
}
/* 
 * Erase cookie with name. 
 * You can also erase/delete the cookie with name. 
 */
function eraseCookie(name) {
  createCookie(name, '', -1);
}

var faves = {
  add: function (new_obj) {
    var old_array = faves.get();

    old_array.push(new_obj);
    faves.create(old_array);
  },

  remove_index: function (index) {
    var old_array = faves.get();

    old_array.splice(index, 1);
    faves.create(old_array);
  },

  remove_id: function (id) {
    var old_array = faves.get();

    var id_index = faves.get_id_index(id);
    faves.remove_index(id_index);
  },

  create: function (arr) {
    var stringified = JSON.stringify(arr);
    createCookie('favespages', stringified);
  },

  get: function () {
    return JSON.parse(readCookie('favespages')) || [];
  },

  get_id_index: function (id) {
    var old_array = faves.get();

    var id_index = -1;
    $.each(old_array, function (index, val) {
      if (val.id == id) {
        id_index = index;
      }
    });

    return id_index;
  },

  update_list: function () {
    $("#appendfavs").empty();
    $.each(faves.get(), function (index, value) {
      var element = '<li class="' + index + '"><h4>' + value.id + '</h4> <a href="' + value.url + '">Open page</a> ' +
        '<a href="javascript:void(0);" class="remove" data-id="' + value.id + '">Remove me</a>';

      $('#appendfavs').append(element);
    });
  }
}

$(function () {
  var url = window.location.href;

  $(document.body).on('click', '#addTofav', function (e) {
    var pageId = window.location.search.match(/ID=(\d+)/)[1];

    if (faves.get_id_index(pageId) !== -1) {
      faves.remove_id(pageId);
    }
    else {
      faves.add({
        id: pageId,
        url: url
      });
    }

    faves.update_list();
  });

  $(document.body).on('click', '.remove', function () {
    var url = $(this).data('id');

    faves.remove_id(url);
    faves.update_list();
  });

  $(window).on('focus', function () {
    faves.update_list();
  });

  faves.update_list();
});
Božo Stojković
  • 2,893
  • 1
  • 27
  • 52