Add and remove favorite items with php Session and ajax

Asked

Viewed 626 times

0

Personal talk,

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

Example of this resource is found on this site: http://www.maximobiliaria.com.br/site_2014/web/vendas

1 answer

1

From what 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");
}

  • This is my friend, although I do not master OO, I will try to implement this class. I will give you a feedback to say if I succeeded.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.