-1

I am working on a real estate website. I have many ads in my website and I need to create a 'favorite' or 'save' button on each of the posts that will save the selected posts in a certain page for user to read later.

I want to use cookies or local storage to keep user favorites on that computer, which would allow users to add items to their favorites and see them again when they return. No account required.

Thanks to one of my friends, I wrote some code but it does not work properly - I mean it does not show any result.

BIG THANKS TO ANYONE THAT CAN HELP!

Here is my current code:

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);
  }
  $(function(){
var faves = new Array();
    var url = window.location.href; // current page url
    $(document.body).on('click','#addTofav',function(e){
      e.preventDefault();
      var pageTitle = $(document).find("title").text();
      var fav = {'title':pageTitle,'url':url};
      faves.push(fav);
      var stringified = JSON.stringify(faves);
      createCookie('favespages', stringified);
      location.reload();
    });
    $(document.body).on('click','.remove',function(){
      var id = $(this).data('id');
      faves.splice(id,1);
      var stringified = JSON.stringify(faves);
      createCookie('favespages', stringified);
      location.reload();
    });

     var myfaves = JSON.parse(readCookie('favespages'));
     faves = myfaves;
    $.each(myfaves,function(index,value){
      var element = '<li class="'+index+'"><h4>'+value.title+'</h4> <a href="'+value.url+'">Open page</a>  '+
      '<a href="javascript:void(0);" class="remove" data-id="'+index+'">Remove me</a>';
      $('#appendfavs').append(element);
    });
  });
 <a href="javascript:void(0);" id="addTofav">Add me to fav</a>

  <ul id="appendfavs">

  </ul>
Malekian
  • 315
  • 8
  • 27
  • may i know what browser you've used? since safari has cookies size limit. Make sure your cookies size not over-sized. Store it on local storage will be good idea. – Fadhly Permata Jul 01 '16 at 09:51
  • thank you for your answering. i want it to be practical in any browser google crome, fire fox or IE. because it depends on my website users and they can use each of them. i really appreciate if you can help me because it is really important to me – Malekian Jul 01 '16 at 10:16
  • 2
    "I wrote some code but it does not work properly" is not a question. Please review [ask] and update your question to be an **actual question**. Otherwise this is [off-topic (#1)](/help/on-topic) and should be closed as such. – zzzzBov Jul 01 '16 at 20:22

1 Answers1

1

I would recommend to prefer the storage of the favorites via the local storage and fall back to to cookies if local storage is no available.

So I implemented a short example how to to use the local storage based on your example.

   var chance;
   var favorites;
   var storage;

   $(document).ready(function() {
     chance = new Chance(); // Just for random hash generation
     if (window.Storage != undefined) {
       storage = window.localStorage;
       if (storage.favorites == undefined) {
         favorites = [];
       } else {
         favorites = JSON.parse(storage.favorites);
       }
       updateList();

       $('#fav').click(function() {
         addFavorite(window.location);
         updateList();
       });

       $('#list').on('click', 'li a', function() {
         deleteFavorite($(this).data('id'));
         updateList();
       });
     } else {
       // No support for local storage
       // Fall back to cookies or session based storage
     }
   });

   function addFavorite(url) {
     favorites.push({
       id: chance.hash({
         length: 15
       }),
       url: url
     });
     storage.setItem('favorites', JSON.stringify(favorites));
   }

   function deleteFavorite(id) {
     for (var i in favorites) {
       if (favorites[i].id == id) {
         favorites.splice(i, 1);
       }
     }
     storage.setItem('favorites', JSON.stringify(favorites));
   }

   function updateList() {
     $('#list').empty();
     if (typeof favorites !== 'undefined' && favorites.length > 0) {
       for (var i in favorites) {
         $('#list').append('<li>' +
           favorites[i].url.href +
           '&nbsp;&nbsp;&nbsp;&nbsp;' +
           '<a class="delete" href="#" data-id="' + favorites[i].id + '">delete</a>' +
           '</li>');
       }
     } else {
       $('#list').append('<li>Nothing stored!</li>');
     }
   }
<script src="https://cdnjs.cloudflare.com/ajax/libs/chance/1.0.3/chance.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="fav" href="#">Add</a>

<ul id="list">
</ul>

EDIT: Added JsFiddle link: https://jsfiddle.net/Wachiwi/r2r3097q/13/

Wachiwi
  • 312
  • 5
  • 15
  • hi thank you very much you are a life saver i just have a qustion now. in this case user have to fill the input and click the add button i want to automatically save page url or id in favorite page. for example my page address is like this: http://localhost/viewmore.php?ID=10 – Malekian Jul 01 '16 at 12:00
  • you can just change the parameter of the call `addFavorite()` to `window.location` if you want to store the url. For storing a parameter there are different solutions like [here](http://stackoverflow.com/a/11582513/5218371) – Wachiwi Jul 01 '16 at 12:36
  • thank you i check it now and also if i want to have a delete option in my favorite page what can i do? you know if sombody wants to delete some of the favorit links – Malekian Jul 01 '16 at 12:40
  • You Can add an id to the stored object and can filter for that id and delete it from the List. I will update the code example later today to add a delete function – Wachiwi Jul 01 '16 at 12:49
  • @user6362236 updated the snippet and the JsFiddle link with a basic version where you can and delete items from the list. Sometimes it behaves kinda weird in JsFiddle – Wachiwi Jul 01 '16 at 16:31
  • hi thank you. your previous code works great but in this code when i open the page where i write the code more than 3 hundred undefined shows up. i do not know why? – Malekian Jul 01 '16 at 20:09
  • like the photo i attached above – Malekian Jul 01 '16 at 20:17
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/116233/discussion-between-user6362236-and-wachiwi). – Malekian Jul 01 '16 at 20:25
  • exactly like the JsFiddle result – Malekian Jul 01 '16 at 20:41
  • hi man excuse me i did not see your last comment in chat room. thank you for your update code. i checked it now but unfortunately it did not work when i click on add it does not show anything. – Malekian Jul 05 '16 at 17:11
  • ok i find out something just now. i run your code with firefox and it is working great i can add and delete. but in google chrome it does not work. do you know why?it does not work in IE too. – Malekian Jul 05 '16 at 17:16
  • For me it works in Safari, Firefox and Chrome. Can't test it on IE. Try to delete the local storage key first and then retry. – Wachiwi Jul 06 '16 at 10:10