I am trying to get the current product ID (if is a product page) in this AJAX call. I have attempted to use global $product but couldn't make it work. Is there any way to access the current product (post) in an AJAX call?
add_action('wp_ajax_get_product_list', 'get_product_list');
add_action('wp_ajax_nopriv_get_product_list', 'get_product_list');
function get_product_list()
{
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'name',
'order' => 'ASC'
);
$loop = new WP_Query($args);
$allProducts = '';
//if the product page get the current product ID
// Do something here with the current product ID
foreach ($loop->posts as $product) {
$allProducts = $allProducts . '<option value="' . $product->ID . '">' . $product->post_title . '</option>';
}
wp_reset_query();
echo $allProducts;
wp_die();
}
AJAX call
jQuery(document).ready(function($) {
var data = {
'action': 'get_product_list',
};
jQuery.post("/wp-admin/admin-ajax.php", data, function(response) {
console.log(response);
});
});
Related
I have been trying to make an autocomplete dropdown list but I really have no idea on how to do it. I have found an example on youtube but sadly it is not for cakephp. Here is the link if you are curious: https://www.youtube.com/watch?v=S6yCBggCKl0&t=305s. Please help me.
The CakePHP version of the project I'm working with is 3.8.
Here are the code the I come up with so far:
view:
$('.js-data-example-ajax').select2({
ajax: {
url: "<?php echo Router::url(["controller"=>"VScripts","action"=>"searchTask"]); ?>",
dataType: "json",
delay: 250,
data: function (params) {
return {
q: params.term,
};
},
processResults: function (data) {
return {
results: data,
};
},
cache: true
},
placeholder: 'Type atleast 1 digit to search',
minimumInputLength: 1
});
Controller:
public function searchTask()
{
$this->autoRender = false;
$term = $this->request->query['q'];
$select = array(
'task_id' => 'id',
);
$tasksTable = TableRegistry::getTableLocator()->get('Tasks');
$tasks = $tasksTable
->find()
->select($select)
->from('tasks')
->where(['task_id' => '%' . $term . '%'])
->limit(10)
->order(['task_id' => 'ASC'])
->execute()
->fetchAll('assoc');
$result = array();
foreach ($tasks as $task) {
$id = $task['task_id'];
$result[] = array('id' => $id, 'text' => $id);
}
echo json_encode($result);
}
I am new to Laravel. Add to cart button to add same product into cart with +1 quantity.
Trying to check if stock greater than qty. When one item is qty 3 than 2 stock I would like to display some text "The requested qty is not available" instead of form submit. Is this possible?
Total Stock have 2.
The problem is that more add to cart to same product into +1 quantity. Nothing prevent add to cart “The requested qty is not available”. can anyone help me please.
In Controller
public function add_to_cart(Request $request)
{
$name = $request->product_name;
$price = $request->product_price;
$itemno = $request->product_itemno;
$qty = $request->product_quantity;
$color = $request->product_color;
$size = $request->product_size;
$stock = products::join('stocks', 'stocks.pid', 'products.id')
->join('sizes', 'sizes.pid', 'products.id')
->where([['products.item_no', '=', $itemno],['sizes.size_name', '=', $size]])
->first();
// Current stock quantity
$stockqty = $stock->qty;
if($qty <= $stockqty)
{
echo "<p>was successfully added to your shopping cart</p>";
Cart::add([
'id' => $itemno,
'weight' => 500,
'name' => $name,
'price' => $price,
'qty' => $qty,
'color' => $color,
'size' => $size
]);
}
else
{
echo "<p>The Requested quantity for this product is not available.</p>";
}
}
In Ajax
$(document).ready(function()
{
$(document).on('click','#add_to_cart',function (e) {
var cart_count = $('.navbar-tool-badge').text();
cart_count = parseInt(cart_count);
if($('input[type=radio][name=size]:checked').length == 0)
{
$('.msg').html('Please choose size.');
return false;
} else {
var product_name = $('#hidden-name').val();
var product_price = $('#hidden-price').val();
var product_itemno = $('#itemno').val();
var product_quantity = $('.quantity').val();
var product_color = $('#color').val();
var product_size = $("input[name='size']:checked").val();
e.preventDefault();
$.ajax
({
method:"POST",
url: "{{ route('add_to_cart')}}",
data:{
"_token": "{{ csrf_token() }}",
product_name:product_name,
product_price:product_price,
product_itemno:product_itemno,
product_quantity:product_quantity,
product_color:product_color,
product_size:product_size},
cache: false,
success: function(response)
{
$("#getCode").html(response);
$("#myModal").modal('show');
}
});
}
});
});
You can put the value for each product quantity added to cart in the session, whenever add_to_cart is executed. Something like below should work.
public function add_to_cart(Request $request)
{
//You should get only the id of the product and cart from the frontend
//via ajax request
//Then you should fetch the Product record from database for that id
$product = Product::findOrFail($request->pid);
$cart = Cart::findOrFail($request->cid);
$sessionKey = "Cart-{$cart->id}-{$product->id}";
$session = $request->session();
$requestedQty = $request->product_quantity;
$desiredQty = 0;
//Get the stock data
$stock = products::join('stocks', 'stocks.pid', 'products.id')
->join('sizes', 'sizes.pid', 'products.id')
->where([
['products.item_no', '=', $itemno],
['sizes.size_name', '=', $size]
])
->first();
// Current stock quantity
$stockqty = $stock->qty;
//If the requested quantity is greater than the available stock
//when the product is added for the first time, send out of stock
if($requestedQty > $stockqty) {
echo "<p>The Requested quantity for this product is not available.</p>";
}
//When a product is added for the first time session won't have entry
if(empty($session->get($sessionKey)){
$desiredQty = $requestedQty;
$session->put($sessionKey, $requestedQuantity);
} else {
$desiredQty = $session->get($sessionKey) + $requestedQty;
}
if($desiredQty > $stockqty) {
echo "<p>The Requested quantity for this product is not available.</p>";
}
//Overwrite the session entry with the new quantity
$session->put($sessionKey, $desiredQty);
echo "<p>was successfully added to your shopping cart</p>";
Cart::add([
'id' => $itemno,
'weight' => 500,
'name' => $name,
'price' => $price,
'qty' => $requestedQty,
'color' => $color,
'size' => $size
]);
}
I'm having difficulty getting this to create a category on the front-end with Ajax. It's 99% working.
Here is my form:
<form id="new_idea" name="new_idea" method="POST">
<ul>
<li>
<label>Idea name</label>
<input type="text" name="idea_name" required />
</li>
<li class="full">
<label>Description</label>
<input type="text" name="idea_description" />
</li>
</ul>
</form>
Here is my function (in functions.php):
add_action( 'wp_ajax_add_new_idea', 'add_new_idea' );
add_action( 'wp_ajax_nopriv_add_new_idea', 'add_new_idea' );
function ajax_scripts() {
$parameters = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('inputs')
);
wp_enqueue_script('my-ajax', get_template_directory_uri().'/js/ajax.js', array('jquery'), null, true);
wp_localize_script('my-ajax', 'inputs', $parameters );
}
add_action('wp_enqueue_scripts', 'ajax_scripts');
function ajaxStatus($status, $message, $data = NULL) {
$response = array (
'status' => $status,
'message' => $message,
'data' => $data
);
$output = json_encode($response);
exit($output);
}
// New Idea
function add_new_idea() {
if(isset($_POST["new_idea_form"])) {
ajaxStatus('error', 'No need to update anything.');
} else {
$nonce = $_POST['nonce'];
if(wp_verify_nonce($nonce, 'inputs') !== false) {
require_once(ABSPATH . 'wp-admin/includes/taxonomy.php');
$idea_name = $_POST['idea_name'];
$idea_description = $_POST['idea_description'];
$idea_slug = sanitize_title_with_dashes($idea_name);
$idea = array(
'cat_name' => $idea_name,
'category_parent' => '',
'category_nicename' => $idea_slug,
'category_description' => $idea_description,
'taxonomy' => 'ideas'
);
wp_insert_category( $idea );
//print_r($idea);
//die;
// Success message
ajaxStatus('success', 'Added new idea');
} else {
// No nonce!
ajaxStatus('error', 'Nonce failed!');
}
}
}
...and this is my ajax.js:
$('#new_idea').on('submit', function(e) {
e.preventDefault();
$.post( inputs.ajaxurl, {
action : 'add_new_idea',
nonce : inputs.nonce,
post : $(this).serialize()
},
function(response) {
console.log(response);
ResponseSuccess(response);
});
return false;
});
As for troubleshooting, if I hardcode values into the $idea array like this and submit the form...
$idea = array(
'cat_name' => 'cool idea',
'category_parent' => '',
'category_nicename' => 'cool-dea',
'category_description' => 'a description of my cool idea',
'taxonomy' => 'ideas'
);
...it actually works and my category gets created.
So from what I can tell, the real problem is that it is not getting the $_POST[] values that were submitted, although I can't see why.
Any help would be awesome.
Try this code.
function add_new_idea() {
$params = array();
parse_str($_POST["post"], $params);
if(isset($_POST["post"])) {
ajaxStatus('error', 'No need to update anything.');
} else {
$nonce = $_POST['nonce'];
if(wp_verify_nonce($nonce, 'inputs') !== false) {
require_once(ABSPATH . 'wp-admin/includes/taxonomy.php');
$idea_name = $params['idea_name'];
$idea_description = $params['idea_description'];
$idea_slug = sanitize_title_with_dashes($idea_name);
$idea = array(
'cat_name' => $idea_name,
'category_parent' => '',
'category_nicename' => $idea_slug,
'category_description' => $idea_description,
'taxonomy' => 'ideas'
);
wp_insert_category( $idea );
//print_r($idea);
//die;
// Success message
ajaxStatus('success', 'Added new idea');
} else {
// No nonce!
ajaxStatus('error', 'Nonce failed!');
}
}
}
Read This
you need to use parse_str for serlize object.
Retrieving serialize data in a PHP file called using AJAX
I have two tables categories and subcategories where categories hasMany subcategories relation.
I have another table products which is related to categories and subcategories.
In add method of products I want to select category from the list and then subcategory associated with particular category selected.
echo $this->Form->input('category_id', ['options' => $categories, 'empty' => true]);
echo $this->Form->input('subcategory_id', ['options' => $subcategories]);
echo $this->Form->input('product_type_id', ['options' => $productTypes]);
echo $this->Form->input('title');
As there is no js helper in CakePHP 3. How could I do this using Ajax.
I'm new to CakePHP and Ajax as well. And currently this show all subcategories in the list.
I get it working like this and its working fine.
view file contain
<?= $this->Form->input('categories', ['options' => $categories, 'empty' => 'Select', 'id' => 'categories']) ?>
<?= $this->Form->input('subcategory_id', ['type' => 'select', 'id' => 'subcategories]) ?>
and myAjax.js file contain
$('#categories').change(function () {
var dataSet = {category_id: $(this).val()};
var requestUrl = appBaseUrl+'products/ajax-subcategories';
$.ajax({
type: "POST",
url: requestUrl,
data: dataSet,
success: function(result) {
$('#subcategories').html(result);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
and ajaxSubcategories action inside ProductsController.php
public function ajaxSubcategories()
{
$this->autoRender = false;
$this->loadModel('Subcategories');
$category_id = $this->request->data['category_id'];
$subcategories = $this->Subcategories->find()
->where(['category_id' => $category_id, 'deleted' => false, 'status' => 0]);
$data = '';
foreach($subcategories as $subcategory) {
$data .= '<option value="'.$subcategory->id.'">'.$subcategory->title.'</option>';
}
echo $data;
}
Hope this might help someone.
I am using codeigniter 2.2.2 with HMVC and a custom session library
I have two views I'll call them V1.php and V2.php for simplicity
and in each view I have a product that can be added to the cart via ajax when you click on the button:
<button class="add-to-cart" id="123" type="button" class="btn btn-fefault cart">
both V1.php and V2.php are sending product details to a controller cart.php to the method add() via ajax
and here is the ajax call in both V1.php and V2.php
$(".add-to-cart").click(function()
{
var target_url = '<?php echo(base_url()."cart/add") ; ?>';
var prod_id = $(this).attr("id");
var qty = 1;
// prepare the data to be sent
var ProductData = {product_id:prod_id,quantity:qty};
$.ajax(
{
url : target_url,
type: "POST",
data : ProductData,
success: function(data)
{
cart = JSON && JSON.parse(data) || $.parseJSON(data);
$("#cart_num").html("( " + cart.num_of_items + " )");
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#cart_notice").show();
$("#cart_notice").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
// prevent default
return false;
});
and here is the controller cart.php
public function add()
{
$product_id = $this->input->post('product_id');
$quantity = $this->input->post('quantity');
// prepare the array for the cart
$data = array(
'id' => $product_id,
'qty' => $quantity,
'price' => 39.95,
'name' => 'T-Shirt',
'options' => array('Size' => 'L', 'Color' => 'Red')
);
// insert the array in the cart
$cart_flag = $this->cart->insert($data);
//$cart_flag returns false if something went wrong
//$cart_flag returns an id if everything is ok
// prepare the array for the ajax callback function
$cart = array(
'num_of_items' => $this->cart->total_items(),
'total_price' => $this->cart->total()
);
echo json_encode($cart);
}
thanks to debugging tools I could see that :
1.when I add the product from V1.php everything is fine ($cart_flag returns an id)
but
2.when I add the product from V2.php it doesn't add anything ($cart_flag returns FALSE ) although $data is the same in both cases
what I'm I doing wrong ?
the answer was casting, it really gave me a hard time but at last I found it,
the $data looked the same but the type was not
this fixes the problem
$data = array(
'id' => (int)$product_id,
'qty' => (int)$quantity,
'price' => 39.95,
'name' => 'T-Shirt',
'options' => array('Size' => 'L', 'Color' => 'Red')
);
hope this helps someone else with the same issue