Перейти до вмісту
Пошук в
  • Детальніше...
Шукати результати, які ...
Шукати результати в ...

Удалять товар из wishlist кнопкой без перезагрузки


Recommended Posts

В wishlist удаление товара из закладок реализовано ссылкой, вот так - имя_сайта/index.php?route=account/wishlist&remove=57 Таки способом удаление происходить с перезагрузкой страницы. Как это реализовать с помощью аджакса? Я так понимаю, что нужно сделать по принципу как у корзины, где есть onclick=cart.remove('6');"

Подскажите пожалуйста как это реализовать?

Надіслати
Поділитися на інших сайтах


добавление в вишлист на кнопке onclick="wishlist.add('id_tovara');
дальше идём в файл с жавой (/catalog/view/javascript/common.js) и смотрим 282 строку, внутри неё есть var wishlist = { 'add': function(product_id) готовая к использованию, и пустая 'remove': function() {

далее на основе add нужно дополнить remove
потом в контроллере (/catalog/controller/account/wishlist.php) на основе функции add сделать функцию remove, так как пост запрос из аякса она не увидит.
потом дописываем кнопку в шаблоне для вишлиста, всё.
по крайней мере в моей версии опенкарта это так выглядит, и на мой взгляд план действий такой

Надіслати
Поділитися на інших сайтах


  • 2 weeks later...

в конец  controller/account/wishlist.php 
 

Спойлер



public function remove(){


        $this->load->language('account/account');
        $this->load->language('account/wishlist');

		$json = array();
		
		$this->load->model('catalog/product');

		if (isset($this->request->post['product_id'])) {
            $product_id = $this->request->post['product_id'];
        } else {
            $product_id = 0;
        }

        $product_info = $this->model_catalog_product->getProduct($product_id);

        if (isset($this->request->post['product_id']) )  {
            // Remove product of Wishlist
            if ($this->customer->isLogged()) {

				$this->load->model('account/wishlist');
                $this->model_account_wishlist->deleteWishlist($this->request->post['product_id']);
            } else {
                $key = array_search($this->request->post['product_id'], $this->session->data['wishlist']);
                if ($key !== false) {
                    unset($this->session->data['wishlist'][$key]);
                }
			}
			$json['redirect'] = $this->url->link('account/wishlist', '', true);

        }


        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
	}


 


в шаблон  account/wishlist.php 

html  

Спойлер



<button  class="wishlist_remove btn" data-product-id="{{ product.product_id}}">
     <i class="bi bi-x"></i>
</button>

 

 



JS
 

Спойлер



<script type="text/javascript"><!--

$('.wishlist_remove').on('click', function() {
   console.log("whislist remove:", $(this).data('product-id'));
   //return
    $.ajax({
      url: "index.php?route=account/wishlist/remove",
      type: "post",
      data: "product_id=" + $(this).data('product-id'),
      dataType: "json",
      success: function (json) {
        $(".alert-dismissible").remove();
        if (json["redirect"]) {
          location = json["redirect"];
        }

        if (json["success"]) {
          console.log(json["success"]);
          $("#content").prepend('<div class="alert alert-success alert-dismissible"><i class="fa fa-check-circle"></i> ' +  json["success"] +  ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>');
        }
        //$("#wishlist-total span").html(json["total"]);
        //$("#wishlist-total").attr("title", json["total"]);

        $("html, body").animate({ scrollTop: 0 }, "slow");
      },
      error: function (xhr, ajaxOptions, thrownError) {
        alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
      },
    });
});    
//--></script> 


 

 

  • +1 1
Надіслати
Поділитися на інших сайтах


В 25.08.2020 в 17:08, DImNSk сказал:

в конец  controller/account/wishlist.php 
 

  Показать контент

 



public function remove(){


        $this->load->language('account/account');
        $this->load->language('account/wishlist');

		$json = array();
		
		$this->load->model('catalog/product');

		if (isset($this->request->post['product_id'])) {
            $product_id = $this->request->post['product_id'];
        } else {
            $product_id = 0;
        }

        $product_info = $this->model_catalog_product->getProduct($product_id);

        if (isset($this->request->post['product_id']) )  {
            // Remove product of Wishlist
            if ($this->customer->isLogged()) {

				$this->load->model('account/wishlist');
                $this->model_account_wishlist->deleteWishlist($this->request->post['product_id']);
            } else {
                $key = array_search($this->request->post['product_id'], $this->session->data['wishlist']);
                if ($key !== false) {
                    unset($this->session->data['wishlist'][$key]);
                }
			}
			$json['redirect'] = $this->url->link('account/wishlist', '', true);

        }


        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
	}

 

 

 

 


в шаблон  account/wishlist.php 

html  

  Показать контент

 



<button  class="wishlist_remove btn" data-product-id="{{ product.product_id}}">
     <i class="bi bi-x"></i>
</button>

 

 



JS
 

  Показать контент

 



<script type="text/javascript"><!--

$('.wishlist_remove').on('click', function() {
   console.log("whislist remove:", $(this).data('product-id'));
   //return
    $.ajax({
      url: "index.php?route=account/wishlist/remove",
      type: "post",
      data: "product_id=" + $(this).data('product-id'),
      dataType: "json",
      success: function (json) {
        $(".alert-dismissible").remove();
        if (json["redirect"]) {
          location = json["redirect"];
        }

        if (json["success"]) {
          console.log(json["success"]);
          $("#content").prepend('<div class="alert alert-success alert-dismissible"><i class="fa fa-check-circle"></i> ' +  json["success"] +  ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>');
        }
        //$("#wishlist-total span").html(json["total"]);
        //$("#wishlist-total").attr("title", json["total"]);

        $("html, body").animate({ scrollTop: 0 }, "slow");
      },
      error: function (xhr, ajaxOptions, thrownError) {
        alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
      },
    });
});    
//--></script> 

 

 

 

 

 

Спасибо!!!

Надіслати
Поділитися на інших сайтах


Створіть аккаунт або увійдіть для коментування

Ви повинні бути користувачем, щоб залишити коментар

Створити обліковий запис

Зареєструйтеся для отримання облікового запису. Це просто!

Зареєструвати аккаунт

Вхід

Уже зареєстровані? Увійдіть тут.

Вхід зараз

×
×
  • Створити...

Important Information

На нашому сайті використовуються файли cookie і відбувається обробка деяких персональних даних користувачів, щоб поліпшити користувальницький інтерфейс. Щоб дізнатися для чого і які персональні дані ми обробляємо перейдіть за посиланням . Якщо Ви натиснете «Я даю згоду», це означає, що Ви розумієте і приймаєте всі умови, зазначені в цьому Повідомленні про конфіденційність.