Adding and removing favorite items with session php and ajax

0

Personal speech,

I need to implement a feature on my site, which will allow the user to select the properties of their liking by clicking a "add to favorites" button, and clicking again can remove that item. I know I can use php and ajax sessions, but I do not know exactly how to do it. Could someone give me an idea or example of this application?

Example of this resource can be found on this site: link

    
asked by anonymous 29.06.2015 / 20:03

1 answer

1

So I understand you want to know how to make a shopping basket, so I suggest you do something like this:


session_start();

class Imoveis
{

private $favorites = [];

    public function addFavorites($product)
    {
      if (isset($_SESSION['cart'])) {
          $this->favorites = unserialize($_SESSION['cart']);
          $this->favorites[] = $product;
      } else {
        $this->favorites[] = $product;
      }
     $this->setCart();
    }

    public function removeFavorites($product)
    {
      if (isset($_SESSION['cart'])) {
          $collection = unserialize($_SESSION['cart']);
      } else {
          $collection = $this->favorites;
      }
         if (count($collection)) {
            foreach ($collection as $key => $productList) {
                  if ($productList == $product) {
                      unset($collection[$key]);
                  }
            }
            $this->favorites = array_values($collection);
         }
        $this->setCart();
    }

    public function setCart()
    {
      $_SESSION['cart'] = serialize($this->favorites);
    }

    public function getCart()
    {
      return unserialize($_SESSION['cart']);
    }

}
//instancia o objeto
$imoveis = new Imoveis();

//adiciona
$imoveis->addFavorites('casa 1');

//remove
$imoveis->removeFavorites('casa 1');

//exibe a lista
$imv =  $imoveis->getCart();

foreach ($imv as $imovel) {
      echo $imovel . nl2br("\n");
}

    
29.06.2015 / 20:45