2016-07-07 4 views
14

Ich entwerfe eine Immobilien-Website. Ich habe viele Anzeigen auf meiner Website und dank meines Freundes Arsh Singh erstelle ich eine "Favorit" oder "Speichern" -Schaltfläche auf jedem der Beiträge, die den ausgewählten Seitentitel auf einer bestimmten Seite basierend auf Cookies speichern, um den Beitrag zu überprüfen wann immer er oder sie will.
Jetzt möchte ich die ID der Anzeige an die Favoritenseite senden, wenn der Benutzer auf "Zu Favoriten hinzufügen" klickt, basierend auf der ID kann ich diese bestimmten Werbungsdaten aus der Datenbank abrufen.
kann ich das tun? Wie? Dies ist mein aktueller Code und kann nur Seitentitel an die Favoritenseite senden. irgendeine Idee?wie man Variablen mit Cookies an die nächste Seite weiterleitet

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

+1

Nur eine kurze Notiz ** über SQL-Injektionen warnen **, ist es gut, dass Sie überprüfen 'is_numeric ($ _ GET [ 'ID' ]) 'aber du solltest auch immer bei le ast 'mysqli_real_escape_string()' http://php.net/manual/de/mysqli.real-escape-string.php. und kann stattdessen folgendes schreiben: $ ID = is_numeric ($ _ GET ['ID'])?$ _GET ['ID']: 1; ':) – antoni

Antwort

0

Hier ist Code Refactoring, die besser (von SO answer) funktioniert:

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

JSON Cookie können Sie JSON verwenden, um die Details zu speichern (id, Post Name, usw.) in einem Cookie durch die Serialisierung JSON: jquery save json data object in cookie

Aber Sie sollten nicht Datenbanktabellennamen in Cookies aus Sicherheitsgründen speichern.

PHP Cookies zugreifen https://davidwalsh.name/php-cookies

+1

Beachten Sie auch genau, wie Cookies im HTTP-Datenstrom gehandhabt werden: Es gibt immer eine" Rundreise "zwischen Client und Host. Sie können die Cookie-Übertragung im HTTP * -Header * mithilfe der Debugging-Funktionen eines beliebigen Browsers sehen. ** LQQK ** dabei, um genau zu sehen, was wann und wie weitergegeben wird. (Und das * wird * wie erwartet weitergegeben. "Niemals annehmen ...") –

+0

@Mike Ah ja ... Annahmen ... der Fluch jedes Programmierers – Jonathan

3

würde ich reine PHP ... setcookie() ein Cookie zu setzen, und lesen Sie es wieder bei der Verwendung von PHP $ _COOKIE benötigt. Da es notwendig wäre, viele strukturierte oder verwandte Daten zu speichern, würde ich dann ein assoziatives Array erstellen, es entsprechend ausfüllen und dann PHP serialize() verwenden, bevor es in einem Cookie gespeichert wird; unserialize() beim Lesen:

Ersparnis:

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

Dann $ data-Array verwenden je nach Bedarf. Wenn ich mit diesen Daten etwas Javascript benötigen würde würde ich einfach tun:

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

Oder mit Schleifen gehe schicker mehr Vars von $ data zu schreiben usw.

+0

danke für deine Antwort. Wie du in meiner Frage siehst, habe ich Cookies auf pure php gesetzt. und es funktioniert gut, aber ich möchte einige andere Optionen hinzufügen wie Cookie mit der Schaltfläche klicken oder die bestimmte Seite ID aus Cookies löschen, wenn ein Benutzer zweimal auf "zu Favoriten hinzufügen" klicken, die ich nicht ohne Javascript – Malekian

+0

erreichen kann Wenn Sie auf der Seite bleiben und den Cookie setzen möchten, können Sie ajax zu einem PHP verwenden, der den Cookie setzt ... Verwenden Sie POST, um die ID oder andere Daten an PHP zu senden. Der Cookie ist jedoch bereits festgelegt, sodass die Seite neu geladen werden muss, um die Änderungen zu erhalten –

1

schließlich bekam ich die Antwort. Diese JavaScript-Code ersetzen, anstatt Frage Javascript (favoritecookie.js), und Sie werden sehen, dass es wie ein charm.with arbeitet, kann dies u Code-ID in Cookie speichern und dann abrufen es, wo sich nur wünschen u

<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(); 
 
\t 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); 
 

 
\t 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); 
 
\t } 
 
\t $(document.body).on('click','#addTofav',function(){ 
 
\t  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. 
 
     } 
 
\t var stringified = JSON.stringify(faves); 
 
    createCookie('favespages', stringified); 
 
    location.reload(); 
 
\t }); 
 
\t  $(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>

Verwandte Themen