WooCommerce programmatically deleting from cart - ajax

How do I programmatically remove an item from the Woocommerce cart using AJAX? I tried putting a function in my functions.php file and accessing that but nothing gets deleted. I tried hard-coding product 299 but it doesn't delete. Here's what I did:
functions.php
function remove_item_from_cart() {
$cart = WC()->instance()->cart;
$id = 299;
$cart_id = $cart->generate_cart_id($id);
$cart_item_id = $cart->find_product_in_cart($cart_id);
if($cart_item_id){
$cart->set_quantity($cart_item_id, 0);
}
return true;
}
themes/mine/main.js
$.ajax({
type: 'POST',
dataType: 'text',
url: "http://www.../wp/wp-content/themes/mine/functions.php",
data: {
action: 'remove_item_from_cart'
},
success: function( data ) {
console.log(data);
}
});

Use proper ajax method of wordpress like this: This worked fine for me.
//functions.php
function remove_item_from_cart() {
$cart = WC()->instance()->cart;
$id = $_POST['product_id'];
$cart_id = $cart->generate_cart_id($id);
$cart_item_id = $cart->find_product_in_cart($cart_id);
if($cart_item_id){
$cart->set_quantity($cart_item_id, 0);
return true;
}
return false;
}
add_action('wp_ajax_remove_item_from_cart', 'remove_item_from_cart');
add_action('wp_ajax_nopriv_remove_item_from_cart', 'remove_item_from_cart');
//main.js
$.ajax({
type: "POST",
url: 'http://localhost/your_site/wp-admin/admin-ajax.php',
data: {action : 'remove_item_from_cart','product_id' : '4'},
success: function (res) {
if (res) {
alert('Removed Successfully');
}
}
});

This seems to work.
HTML:
<?php
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
?<
<button class="remove-item" data-cart-item-key="<?=$cart_item_key;?>">
remove item
</button>
<?
}
?>
Javascript:
$('.remove-item').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: ajaxurl,
data: {
action: 'remove_item_from_cart',
'cart_item_key': String($(this).data('cart-item-key'))
}
});
});
In functions.php, inside the template folder:
function remove_item_from_cart() {
$cart_item_key = $_POST['cart_item_key'];
if($cart_item_key){
WC()->cart->remove_cart_item($cart_item_key);
return true;
}
return false;
}
add_action('wp_ajax_remove_item_from_cart', 'remove_item_from_cart');
add_action('wp_ajax_nopriv_remove_item_from_cart', 'remove_item_from_cart');

For WooCommerce 3.0+ you can do it using the built-in remove_cart_item() function
function findCartItemKey($cartItems, $productId){
foreach($cartItems as $cartKey => $item){
$product = $item['data'];
if($product->get_id() == $productId){
return $cartKey;
}
return false;
}
}
global $woocommerce;
$cartItemKey = findCartItemKey($woocommerce->cart->get_cart())
$woocommerce->cart->remove_cart_item($cartItemKey);

Related

I need a dropdown list based on parent using ajax in Laravel 5

Controller Function Code
public function siteadmin_get_subcategory(Request $request)
{
$product_id = $request->input('product');
$sub_category=array(
'product_id'=>$product_id,
);
$return = Category_model::get_subcategory($sub_category);
//return view('siteadmin.get-subcategory',['sub_category' => $sub_category]);
return view('siteadmin.get-subcategory',['sub_category' => $sub_category]);
}
Model Function Code (which gets subcategory on product id)
public static get_subcategory($sub_category)
{
return DB::table('le_product')->where('product_id', '=', $sub_category)->get();
}
View JavaScript Code
This is my Ajax concept for Dropdown list based on parent
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#product_id').change(function(){
var product = $('#product_id').val();
if(product != 0) {
$.ajax({
type:'post',
url:"<?php echo base_url('SiteadminController/siteadmin_getsub_category')?>",
data: { id:product },
cache:false,
success: function(returndata){
$('#subcategory').html(returndata);
}
});
}
})
})
</script>
You need to call the correct URL in your AJAX:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#product_id').change(function(){
var product = $('#product_id').val();
if(product != 0) {
$.ajax({
type:'post',
url:"<?php echo action('SiteadminController#siteadmin_getsub_category')?>",
data: { id:product },
cache:false,
success: function(returndata){
$('#subcategory').html(returndata);
}
});
}
})
})
</script>
Also AJAX is expecting JSON, from what I see, you will return HTML. So you need to make a Controller action to return JSON.
get_subcategory1
public function get_subcategory1()
{
/*$product_id = $request->input('product_id');
$data=array(
'product_id'=>$product_id,
);*/
//$get_subcategory1 = Category_model::get_subcategory1();
return view('siteadmin.get-subcategory1');
}

laravel 4 upvote via ajax post

I can't seem to get my voting system to work in ajax. I'm trying to establish the 'upvote' and have my onclick function call my route and insert a vote accordingly, except nothing happens. I can't see why or where I'm going wrong.
JAVASCRIPT
$( document ).ready(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
alert(dataString);
$(this).fadeIn(200).html('<img src="/img/vote-up-on.png" />');
$.ajax({
type: "POST",
url: "http://domain.com/knowledgebase/upvote",
dataType: "json",
data: {id : id},
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
if (name=='down')
{
alert(dataString);
$(this).fadeIn(200).html('<img src="/img/vote-down-on.png" />');
$.ajax({
type: "POST",
url: "downvote",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
</script>
ROUTE.PHP
Route::get('knowledgebase/upvote/{id}', 'PostController#upvote');
POSTCONTROLLER.PHP
public function upvote($id)
{
if (Auth::user()) {
if (Request::ajax()) {
$vote = "1";
$user = Auth::user()->id;
$post = Post::find($id);
$checkvotes = Vote::where('post_id', $post->id)
->where('user_id', $user)
->first();
if (empty($checkvotes))
{
$entry = new Vote;
$entry->user_id = $user;
$entry->post_id = $post->id;
$entry->vote ="1";
$entry->save();
}
}
}
else
{
return "Not an AJAX request.";
}
}
You are using post in your jquery, but you are waiting for a GET route.
Use...
Route::post('knowledgebase/upvote/{id}', 'PostController#upvote');
Additionally, the way you are handling your route may not work correctly with the id. It would be expecting the id in the URL so what you can do is append your id to the url when setting up the ajax.
url: "http://domain.com/knowledgebase/upvote/"+id,
Or not use it at all, take the {id} portion out of your route, and grab it using Input::get('id');

how to retrieve data sent by Ajax in Cakephp?

I have been stuck at this problem for a whole day. What im trying to do is to send 2 values from view to controller using Ajax.
This is my code in hot_products view:
<script>
$(function(){
$('#btnSubmit').click(function() {
var from = $('#from').val();
var to = $('#to').val();
alert(from+" "+to);
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to,
success: function(data){
alert("success");
}
}
});
});
});
and my hot_products controller:
public function hot_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
//code to get data and process it here
}
}
I dont know how to get 2 values which are start_time and end_time.
Please help me. Thanks in advance.
PS: im using cakephp 2.3
$this->request->data gives you the post data in your controller.
public function hottest_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
}
if ($this->request->isPost()) {
// get values here
echo $this->request->data['start_time'];
echo $this->request->data['end_time'];
}
}
Update
you've an error in your ajax,
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to },
success: function(data){
alert("success");
}
});
If you method is POST:
if($this->request->is('ajax'){
$this->request->data['start_time'];
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->data['start_time'];
$this->autoRender = false;
ANd if method is GET:
if($this->request->is('ajax'){
$this->request->query('start_time');
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->query('start_time');
$this->autoRender = false;

how to get the value from codeigniter to ajax?

i have an ajax which I don't know if it is correct. I want to get the value from the controller and pass it to ajax.
ajax:
$.ajax({
type: "GET",
url: swoosh(id, path+'swoosh_employee/swoosh_delete_child', 'childdv'),
success: function(response) {
if (response != "Error")
{
$('#success-delete').modal('show');
}
else
{
alert("Error");
}
}
});
event.preventDefault();
and in the controller:
public function swoosh_delete_child()
{
$P1 = $this->session->userdata('id');
parse_str($_SERVER['QUERY_STRING'],$_GET);
$id = $_GET['h'];
$response = $this->emp->delete_children($id);
}
model
public function delete_chilren($id){
.......//codes here.. etc. etc.
if success //
return "success";
else
return "Error";
}
i just want to pass/get the value of $reponse and pass it to the ajax and check if the value is error or not..
Just echo in the controller:
$response = $this->emp->delete_children($id);
And alert the response:
alert(response); //output: success / Error
in your controller:
you should have something like this
public function swoosh_delete_child(){
$P1 = $this->session->userdata('id');
parse_str($_SERVER['QUERY_STRING'],$_GET);
$id = $_GET['h'];
$response['status'] = $this->emp->delete_children($id);
echo json_encode($response);
}
then in your ajax, to access the response
$.ajax({
type: 'POST',
url: url: swoosh(id, path+'swoosh_employee/swoosh_delete_child', 'childdv'),,
dataType: 'json',
success: function(response){
if (response.status)
{
$('#success-delete').modal('show');
}
else
{
alert("Error");
}
}
});

Yii: get result for ajax request

I have a anchor;
When I click on it, the following code executes:
<script>
$('.viewcnp').click(function() {
event.preventDefault();
var r = prompt("Enter your password:");
if (r) {
$.ajax({
type: "POST",
url: '<?php echo Yii::app()->baseUrl; ?>' + '/index.php/admin/user/viewCnp/id/' + '<?php echo $model->id; ?>',
data: {'password': r},
success: function(data) {
$('.cnpdecrypted').text(data);
},
dataType: 'text'
});
}
});
</script>
this code makes a request to this action:
public function actionViewCnp($id) {
$model = User::model()->findByPk($id);
if ($model) {
return '{"data":"' . Utils::decrypt_cnp($model->cnp) . '"}';
}
else
return false;
}
If in the action I echo the cnp decripted, its there, but i can't set the value because I don't receive it on success.
You should simply use echo instead of return :
if ($model) {
echo Utils::decrypt_cnp($model->cnp);
}

Resources