datatable server side processing gives error - ajax

I am new in codeigniter-4 and i am inplementing datatable server side processing.
I found following error:
"DataTables warning: table id=admin_user_datatable - Requested unknown
parameter '0' for row 0, column 0. For more information about this
error, please see http://datatables.net/tn/4"
After this error, data is loading in server table.
controller:
public function ajaxDataTables()
{
$params['draw'] = #$_POST['draw'];
$start = #$_POST['start'];
$length = #$_POST['length'];
$search_value = #$_POST['search']['value'];
if(!empty($search_value)){
$total_count = $this->db->query("SELECT employee_name,employee_email,employee_phone from users WHERE id like '%".$search_value."%' OR employee_name like '%".$search_value."%' OR employee_email like '%".$search_value."%' OR employee_phone like '%".$search_value."%'")->getResult();
$data = $this->$db->query("SELECT employee_name,employee_email,employee_phone from users WHERE id like '%".$search_value."%' OR employee_name like '%".$search_value."%' OR employee_email like '%".$search_value."%' OR employee_phone like '%".$search_value."%' limit $start, $length")->getResult();
}else{
// count all data
$total_count = $this->db->query("SELECT employee_name,employee_email,employee_phone from users")->getResult();
// get per page data
$data = $this->db->query("SELECT employee_name,employee_email,employee_phone from users limit $start, $length")->getResult();
}
$no = #$_POST['start'];
foreach ($data as $employee) {
$no++;
$row = array();
$row[] = $no;
$row[] = $employee->employee_name;
$row[] = $employee->employee_email;
$row[] = $employee->employee_phone;
$row[] ='<span class="role member">Update</span> || <span class="role admin">Delete</span>';
$data[] = $row;
}
$json_data = array(
"draw" => #$_POST['draw'],
"recordsTotal" => count($total_count),
"recordsFiltered" => count($total_count),
"data" => $data // total data array
);
echo json_encode($json_data);
}
<script>
var site_url = "<?php echo site_url(); ?>";
$(document).ready( function () {
$('#admin_user_datatable').DataTable({
paginationType: "full_numbers",
lengthMenu: [[5, 10, 15, 20], [5, 10, 15, 20]],
processing: true,
serverSide: true,
scrollY: "400px",
scrollCollapse: true,
ajax: {
url: site_url + "/ajax-datatable", // json datasource
type: "post",
data: {
// key1: value1 - in case if we want send data with request
}
},
columnDefs: [
{ orderable: false, targets: [0] }
],
bFilter: true, // to display datatable search
});
});
</script>

Related

Get Product ID on AJAX call

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);
});
});

How to use Select2 Ajax on CakePHP?

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);
}

Laravel add to cart button with same product into cart with +1 quantity

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
]);
}

Constraint Violation on dynamic form Symfony

i work on Symfony3.4
I have a dynamic form country->region->city (3 distincts entities).
I can change fields based on user selection without any problem.
But i can't persist in database because of a constraint violation on the field city (and only this field)
And I realy don't know why because I call them (region and city) the same way...
Any help would be welcome.
Here is the Form :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$em = $options['entityManager'];
$builder
->add('rue', TextType::class, array(
'label' => 'votre rue',
'required' => true,
))
->add('pays', EntityType::class, array(
'class' => 'AppBundle\Entity\Pays',
'placeholder' => '--choisir--',
'choice_label' => 'nom',
'required' => true
))
;
$addRegion = function (FormInterface $form, Pays $pays = null) {
$regions = null === $pays ? array() : $pays->getRegions();
$form->add('region', EntityType::class, array(
'class' => 'AppBundle\Entity\Region',
'placeholder' => '--choisir une région--',
'choices' => $regions,
'choice_label' => 'nom',
'required' => true
));
};
$addVille = function (FormInterface $form, Region $region = null) {
$villes = null === $region ? array() : $region->getVilles();
$form->add('ville', EntityType::class, array(
'class' => 'AppBundle\Entity\Ville',
'placeholder' => '--choisir une ville--',
'choices' => $villes,
'choice_label' => 'nom',
'required' => true
));
$form->add('submit', SubmitType::class
);
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($addRegion, $addVille){
$form = $event->getForm();
$addVille($form, null);
$addRegion($form, null);
}
);
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) use ($addRegion, $addVille, $em) {
$form = $event->getForm();
$data = $event->getData();
if(isset($data['pays'])){
$paysId = $data['pays'];
$repo = $em->getRepository('AppBundle\Entity\Pays');
$pays = $repo->find($paysId);
$addRegion($form, $pays);
$addVille($form, null);
}
else if(isset($data['region'])){
$regionId = $data['region'];
$repo = $em->getRepository('AppBundle\Entity\Region');
$region = $repo->find($regionId);
$addVille($form, $region);
}
}
);
}
And here is the Template :
{% block body %}
{% form_theme form 'bootstrap_4_layout.html.twig' %}
{% for message in app.flashes('notice') %}
<div style="color:green;">
{{ message }}
</div>
{% endfor %}
{{ form_start(form) }}
{{ form_errors(form) }}
{{ form_end(form) }}
{% endblock %}
{% block javascripts %}
<script>
var $pays = $('#adresse_pays');
var $region = $('#adresse_region');
var $ville = $('#adresse_ville');
$pays.change(function() {
var $form = $(this).closest('form');
var data = {};
data[$pays.attr('name')] = $pays.val();
// Submit data via AJAX to the form's action path.
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
$ville.empty()
var select = $(html).find('#adresse_ville > option')
$ville.append(select)
$region.empty()
var select = $(html).find('#adresse_region > option')
$region.append(select)
$region.val($("#adresse_region option:first").val());
console.log('regions')
console.log(select)
}
});
});
$region.change(function() {
var $form = $(this).closest('form');
var data = {};
data[$region.attr('name')] = $region.val();
// Submit data via AJAX to the form's action path.
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
$ville.empty()
var select = $(html).find('#adresse_ville > option')
$ville.append(select)
$ville.val($("#adresse_ville option:first").val());
console.log('villes')
console.log(select)
}
});
});
</script>
{% endblock %}
This is the alert on the form (next to city field) :
Error This value is not valid
I went further thanks to the debug bar, and it seems that this field does not send an object but an integer.
The difference i found with another field is that in the city field :
Normalized Format submitted is null
while in another field such as region :
Normalized Format
Region {#6035 ▼
-id: 3
-nom: "Catalogne"
-villes: PersistentCollection {#6039 …}
-pays: Pays {#5802 ▶}
-adresses: PersistentCollection {#6041 …}
}
It works !
i split the function
$builder->addEventListener(
FormEvents::PRE_SUBMIT, ... in half => i remove the else if and made another similar function to listen when "region" is changed.
What bothers me is I don't understand why it works this way but not the other way...
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) use ($addRegion, $addVille, $em) {
$form = $event->getForm();
$data = $event->getData();
if(isset($data['pays'])){
$paysId = $data['pays'];
$repo = $em->getRepository('AppBundle\Entity\Pays');
$pays = $repo->find($paysId);
$addRegion($form, $pays);
$addVille($form, null);
}
}
);
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function(FormEvent $event) use ($addVille, $em) {
$form = $event->getForm();
$data = $event->getData();
if(isset($data['region'])){
$regionId = $data['region'];
$repo = $em->getRepository('AppBundle\Entity\Region');
$region = $repo->find($regionId);
$addVille($form, $region);
}
}
);

YII CListView Ajax multiple TextField filter

I have a CListView which I want to filter using Ajax. I have 2 textfields. Now they both filter the same column: titel. I'm searching quite some time now, but I can't seem to figger out why they both filter the titel and not the locatie too..
It's my first time to use Ajax so, i'm afraid I don't know exactly how to pass the right parameters at the moment and am kind of lost. Someone who can help me?
So here's my view:
<?php echo CHtml::beginForm(CHtml::normalizeUrl(array('kunstwerk/index')), 'get', array('id'=>'filter-form'))?>
<?php echo CHtml::textField('string', (isset($_GET['string'])) ? $_GET['string'] : '', array('id'=>'locatie'));?>
<?php echo CHtml::textField('string', (isset($_GET['string'])) ? $_GET['string'] : '', array('id'=>'titel'));?>
and..
Yii::app()->clientScript->registerScript('search',
"var ajaxUpdateTimeout;
var ajaxRequest;
$('input#titel').keyup(function(){
titel = $(this).serialize();
clearTimeout(ajaxUpdateTimeout);
ajaxUpdateTimeout = setTimeout(function () {
$.fn.yiiListView.update(
// this is the id of the CListView
'ajaxListView',
{data: titel}
)
},
// this is the delay
300);
});
$('input#locatie').keyup(function(){
locatie = $(this).serialize();
clearTimeout(ajaxUpdateTimeout);
ajaxUpdateTimeout = setTimeout(function () {
$.fn.yiiListView.update(
// this is the id of the CListView
'ajaxListView',
{data: locatie}
)
},
// this is the delay
300);
});"
);
and..
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'sortableAttributes'=>array(
'titel'
),
'id'=>'ajaxListView',
));
?>
Here's my controller:
public function actionIndex($string = '')
{
$criteria = new CDbCriteria();
if( strlen( $string ) > 0 )
$criteria->addSearchCondition( 'titel', $string, true, 'OR' );
$criteria->addSearchCondition( 'locatie', $string, true, 'OR' );
$dataProvider = new CActiveDataProvider( 'Kunstwerk', array( 'criteria' => $criteria, ) );
//$dataProvider=new CActiveDataProvider('Kunstwerk');
$this->render('index',array(
'dataProvider'=>$dataProvider,
'bedrijven' => Bedrijf::model()->findAll(),
));
}

Resources