0

I have a PHP code and I get id from another page in it I want to save this variable (id) in cookies with JavaScript. I am new in JavaScript but after a lot of search finally I could wrote some codes. this is my current code please take a look at this I think the problem is how I define
var favID = $ID; in my JavaScript code please help me thanks

p.s.: please do not suggest saving cookie with pure PHP because I did it and it works fine but I want to do some fancier stuff with it for example as you see I want to save id in cookies by click which is not accessible with PHP

    <html>
      <body>
      <a id="addTofav">Add me to fav</a>
    <?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");
    while($row = mysqli_fetch_array($result)):
    $price=$row['price'];
    $rent=$row['rent'];
    $room=$row['room'];
    $date=$row['date']; 
    echo"price";
    echo"room";
    echo"date";
    endwhile;
    ?>
    </body>
    </html>
    /*
      * 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(){
        var favID;
        var query = window.location.search.substring(1);
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            var favID = (pair[0]=='ID' ? pair[1] :1)
        }
        $(document.body).on('click','#addTofav',function(){
        var fav = {'$ID':favID};
        faves.push(fav);
        var stringified = JSON.stringify(faves);
        createCookie('favespages', stringified);
        location.reload();
        });
      var myfaves = JSON.parse(readCookie('favespages'));
        if(myfaves){
        faves = myfaves;
        } else {
        faves = new Array();
        }
      });
6
  • Why don't you use localStorage? Commented Jul 13, 2016 at 9:13
  • Is this JS is in the same php page or included? Commented Jul 13, 2016 at 9:15
  • @Mohit Bhardwaj hi thank you for your answering cookie is basic it is feasible in every browser and beside if i solve this problem i think i can get result and i do not want to start from first step with localstorage Commented Jul 13, 2016 at 9:16
  • @RIYAJ KHAN hi thank you for your answering it can be in the same page i just want to make it easier for reviewers to check codes Commented Jul 13, 2016 at 9:18
  • @Mohit Bhardwaj in one of my codes i used local storage and it worked with google chrome and did not work with firefox. so i decided to use cookies Commented Jul 13, 2016 at 9:19

3 Answers 3

1

The problem is your javascript, which I assume is in a different file, is not aware of PHP. You can do the following to define the $ID in the javascript variable

<html>
    <body>
        <a id="addTofav">Add me to fav</a>
        <?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");
            while($row = mysqli_fetch_array($result)):
                $price=$row['price'];
                $rent=$row['rent'];
                $room=$row['room'];
                $date=$row['date']; 
                echo"price";
                echo"room";
                echo"date";
            endwhile;
        ?>


        <!-- This part is what you want -->


        <script>
            var favID = <?php $ID ?>; // this gets the variable from PHP and saves it in the javascript variable.
            document.cookie = 'my_id='+favID+'; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/' // save it to a cookie
        </script>


       <!-- till here -->


    </body>
</html>

Now on some other page here is how you can get the cookie value:

var nameEQ = "my_id=";
var ca = document.cookie.split(';');
var retrieved_id = null
for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) retrieved_id = c.substring(nameEQ.length,c.length);
}

console.log(retrieved_id) // here you will find your ID

Now I haven't tested this. Theoretically it should work though.

Sign up to request clarification or add additional context in comments.

9 Comments

hi man thank u for your answering i am gonna test your answer as soon as finish my launch and i am gonna ask your opinion about edited code. :)
how about this line am i gonna need to change it var fav = {'$ID':favID};
@user6362236 no you wont need to change it
as isaid i am new in javascript could u please tell me how can i show results. i mean i save the id with this line var stringified = JSON.stringify(faves); and then retrieve it with var myfaves = JSON.parse(readCookie('favespages')); and now how can i show it?
@user6362236 why do you want to save it? once this page loads, your ID will be available to you as favID in javascript. Try logging it to your console.
|
1

After looking your requirement, You should move this $ID = $_GET['ID'] : $ID = 1; on Javascript side.As you say,you want better clean code.Don't messup JS and PHP in single file.It's bad one

You should use javascript to access the parameter passed from URL.

var query = window.location.search.substring(1);
for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    var ID = (pair[0]=='ID' ? pair[1] :1)
}

Then ID is easily available to your JS.

YOUR JS :

$(function(){
    var favID;

    var query = window.location.search.substring(1);
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        var favID = (pair[0]=='ID' ? pair[1] :1)
    }

    $(document.body).on('click','#addTofav',function(){
    var fav = {'$ID':favID};
    faves.push(fav);
    var stringified = JSON.stringify(faves);
    createCookie('favespages', stringified);
    location.reload();
    });

EDIT :

You can use localStorage. on current page

`localStorage.getItem('ID',10)`

On other page where you want to access it. localStorage.getItem('ID');

7 Comments

hi thank u for your answering. i did not get your answer. why i have to move this $ID = $_GET['ID'] : $ID = 1; i mean i have many ads in my website and each of them have a id i send their id to this page and get that id's with this line (is_numeric($_GET['ID'])) ? $ID = $_GET['ID'] : $ID = 1;
i think u did not get this line i write it that way to prevent from sql injection. at first it checks that if id is a number other wise it shows the id=1 results by default
Sorry for move. U dont need to do this thing.Just write the same script in JS way that's it
no problem man. as i said i am new in jacascript. could u please add your code in my javascript code thanks a lot
hey man thanks for your updated code. i edited my javascript code in the above could u please check it and also i assume we could save id in cookie but i have a problem i do not know how to show saved id in other page
|
0

thanks to all of my friends ( RIYAJ KHAN and Anubhav)finally i got the answer. replace this javascript code instead of question javascript 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.