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.
Related
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);
});
});
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 created a form using AJAX because i have several alternatives concerning the fields.
I have correct information in my javascript and make tests... my first select use the following function and generates form
function setParentSector() {
$("#listSectors").html("");
$("#createSector").html("");
if($('#langname option:selected').val() !=0) {
var obj = { 'id': $('#langname option:selected').val() };
if (obj['id'] != 1) {
ajaxSectors(obj);
}
else
{
// another form generated here ...
$('#createSector').append("something else");
}
}
};
I use a "classical" ajax ..
function ajaxSectors(objSetParent) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/admin/ajax/sectorParent',
type: 'post',
dataType: 'json',
async: true,
success: function (result) {
$('#listSectors').append("<label for='langname'>label </label> " +
"<select class='form-control m-input m-input--air' id='sectors' onclick='setLangTranslation()'>" +
"<option value='0' selected>Select value</option></select>" +
"<span class='m-form__help' id='existsAlready'>");
var count = result.length;
for (var i = 0; i < count; i++) {
if (result[i].deleted_at === null) {
$('#sectors').append("<option value='" + result[i].sector_id + "'>" + result[i].sectname + "</option>");
}
else {
console.log("peanuts");
}
}
},
data:objSetParent,
error: function (result) {
},
complete: function (result) {
//console.log("complete");
}
});
}
This part of code works fine and i display what i want...
When I want to save into DB the form, I plan to use the store method and I create the $request->validate()
In the store method I have :
$request->validate([
'admin' => 'required',
'langname' => 'required',
'sectname' => 'required',
'sectshortname' => 'nullable',
]);
return view ('test')
The test view contains just in order to see what i post ..
If i keep the validate part, the page is just refreshed and not validated...
Without the request validate I display the view and i just see the value of the input with the token.
Thanks for your answers. Let's hope my question is "clear" enough
Use this code I hope this code works for you please use this Use Validator;
$rules = [
'admin' => 'required',
'langname' => 'required',
'sectname' => 'required',
'sectshortname' => 'nullable',
];
$data = $request->all();//or you can get it by one by one
$validator = Validator::make($data , $rules);
if ($validator->fails()) {
$error=[];
$errors = $validator->messages();
foreach($errors->all() as $error_msg){
$error[]= $error_msg;
}
return response()->json(compact('error'),401);
}
return view ('test')
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
I have a ajax link in yii when user click it do something and update a element html (content of td) without refresh page how can change 2 element html?
I explain more:
in view i have a table by some td for show information a td for send information (there are a image ajaxlink) and a td by message of content (example: "not send")
When user click image link call a function and valid information (...) and change message of td ('validation is success').("not send" change to "validation is success")
I did what I was told but i want to remove ajaxlink and replace it by a simple image how
can I do it?
i add:
CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/email-send.png", '', array('title' => 'sended success'))
view.php:
<td id="send_<?php echo CHtml::encode($profileInformationServices->id); ?>"><?php echo "not send"; ?></td>
<td id="sended_<?php echo CHtml::encode($profileInformationServices->id); ?>">
<?php
echo $profileInformationServices->send ? CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/email-send.png", '', array( 'title' => 'sended success')):
CHtml::ajaxLink(CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/send.png", '', array(
'title' => 'Send for valid')), Yii::app()->createUrl('/profileInformationService/send'),
array( // ajaxOptions
'type' => 'POST',
'data' => array( 'id' => $profileInformationServices->id ),
'update' => '#send_'.$profileInformationServices->id,
)
);
?>
</td>
controller:
public function actionSend() {
if (Yii::app()->request->isPostRequest) {
$model = $this->loadModel($_POST["id"]);
$model->send = 1;
$model->save();
echo "sended success";
}
}
Use ajaxLink callback to change the text in td.
<?php
//I am keeping your ternary code in if-else condition for readability
if($profileInformationServices->send)
{
echo CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/email-send.png", '', array('title' => 'sended success'));
}
else
{
echo CHtml::ajaxLink
(
CHtml::image(Yii::app()->theme->baseUrl . "/img/gridview/send.png", '', array('title' => 'Send for valid')),
Yii::app()->createUrl('/profileInformationService/send'),
array
(
'type' => 'POST',
'data' => array('id' => $profileInformationServices->id),
'success'=>'function(data)
{
if(data=="sended success")
{
$("#send_'.$profileInformationServices->id.'").html("validation is success");
}
}',
)
);
}
?>