最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to pass variable to next page with cookies - Stack Overflow

programmeradmin0浏览0评论

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=".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>

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);
        });
      });

Share Improve this question edited Jul 14, 2016 at 7:09 Malekian asked Jul 7, 2016 at 16:08 MalekianMalekian 3158 silver badges29 bronze badges 1
  • 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() php.net/manual/en/mysqli.real-escape-string.php. and can write as this instead $ID = is_numeric($_GET['ID']) ? $_GET['ID'] : 1; :) – antoni Commented Jul 12, 2016 at 1:37
Add a comment  | 

4 Answers 4

Reset to default 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

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.

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();
});

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>

发布评论

评论列表(0)

  1. 暂无评论