15

I am designing a real estate website. I have many ads in my website and thanks to my friend Arsh Singh I create a 'favorite' or 'save' button on each of the posts that will save the selected page title in a certain page based on cookies for user to review the post when ever he or she wants.
Now i want to send ad's id to the favorite page when user click on "add to favorites" thus based on id i can fetch that certain ad data from database .
can i do this? how? this is my current code and it can only send page title to the favorite page. any idea?

<!DOCTYPE html>
<html>
<head>
  <title>New page name</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
  <script src=favoritecookie.js></script>
</head>
<body>
  <a href="javascript:void(0);" id="addTofav">Add me to fav</a>
  <ul id="appendfavs">

  </ul>
 
 <?php
 error_reporting(0);
include("config.php");
(is_numeric($_GET['ID'])) ? $ID = $_GET['ID'] : $ID = 1;
$result = mysqli_query($connect,"SELECT*FROM ".$db_table." WHERE idhome = $ID");
?>
<?php while($row = mysqli_fetch_array($result)):
$price=$row['price'];
$rent=$row['rent'];
$room=$row['room'];
$date=$row['date'];
?>
<?php 
echo"price";
echo"room";
echo"date";
?>
 <?php endwhile;?> 

</body>
</html>

//favoritecookie.js
/*
      * 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 = 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
        $(document.body).on('click','#addTofav',function(e){
          e.preventDefault();
          var pageTitle = $(document).find("title").text();
          if(isAlready()){
          } else {
              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'));
         if(myfaves){
           faves = myfaves;
         } else {
           faves = new Array();
         }
        $.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);
        });
      });
Malekian
  • 315
  • 8
  • 27
  • 1
    Just a quick note to **warn about SQL injections**, it's good that you check `is_numeric($_GET['ID'])` but you should also always use at least `mysqli_real_escape_string()` http://php.net/manual/en/mysqli.real-escape-string.php. and can write as this instead `$ID = is_numeric($_GET['ID']) ? $_GET['ID'] : 1;` :) – antoni Jul 12 '16 at 01:37

4 Answers4

4

JSON in Cookie You can use JSON to store the details (id, post name, etc) into a cookie by serialising the JSON: jquery save json data object in cookie

However you should not store database table names in cookies for security's sake.

PHP cookies access https://davidwalsh.name/php-cookies

Community
  • 1
  • 1
sunfffd
  • 141
  • 6
  • 1
    Also bear in mind exactly how cookies are handled in the HTTP data stream: there's always a "round trip" between client and host. You can see the cookie transfer in the HTTP *header* using the debugging features of any browser. **LQQK** at it, to see exactly what is being passed, when, and how. (And, that it *is* being passed as you expect. "Never assume ...") – Mike Robinson Jul 08 '16 at 13:41
  • @Mike Ah yes... assumptions... the bane of every programmer – Jonathan Jul 09 '16 at 16:28
3

I would use pure PHP... setcookie() to place a cookie, and read it back when needed using PHP $_COOKIE. Since there would be a need to store a lot of data, structured, related or not, I would then create an associative array, fill it accordingly and then use PHP serialize() it before save it in a cookie; unserialize() when reading:

Saving:

a) $data = array("ID"=>value, "otherdata"=>value...etc);
b) $dataPacked = serialize($data);
c) setcookie("cookieName", $dataPacked);

Reading:

a) $dataPacked = $_COOKIE["cookieName"];
b) $data = unserialize($dataPacked);

Then use $data array as needed. If I would need some Javascript with that data I would simply do:

<script>
var jsVar = "<?php echo $data['key'];?>";

Or go fancier with loops to write more vars from $data, etc.

Aram Alvarez
  • 536
  • 6
  • 21
  • thank you for your answering. as u see in my question i added, set cookie based on pure php. and it is working well but i want to add some other options to it like set cookie with button click or delete the certain page id from cookies if a user click twice on "add to favorites" which i can not achive them without using javascript – Malekian Jul 13 '16 at 06:06
  • if you want to stay in the page and still set the cookie, you can use ajax to a php that sets the cookie...use POST to send the ID or whatever data to the PHP. However the cookie is already set, so the page needs to reload to get the changes – Aram Alvarez Jul 13 '16 at 15:29
1

finally i got the answer. replace this javascript code instead of question javascript (favoritecookie.js) and you will see that it works like a charm.with this u code can save id in cookie and then retrieve it where ever u want

<script>
   /*
  * 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);
 }
 $(document.body).on('click','#addTofav',function(){
       if(isAlready()){
      } else {
          var fav = {'favoriteid':favID,'url':url};
          faves.push(fav);//The push() method adds new items (fav) to the end of an array (faves), and returns the new length.
      }
 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'));
    if(myfaves){
    faves = myfaves;
    } else {
    faves = new Array();
    }
    $.each(myfaves,function(index,value){
      var element = '<li class="'+index+'"><h4>'+value.favoriteid+'</h4>   '+
      '<a href="javascript:void(0);" class="remove" data-id="'+index+'">Remove me</a>';
      $('#appendfavs').append(element);
    });

});
 </script>
Malekian
  • 315
  • 8
  • 27
1

Here is refactored code that works better (from SO answer):

/* 
 * 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();
});
Community
  • 1
  • 1
Božo Stojković
  • 2,893
  • 1
  • 27
  • 52