Laravel DataTables multiple select with checkboxes - php

I am developing an application in Laravel with DataTables where i display data form Mysql database. How to do multiple selection with line color for each selection ? like this link but with multiple selection and how to get values from the selected line not just the line id and how to get the current line values when click on the corresponding button of that line ?
Each button of the last column open a form with a submit button, the submit function is for all the blue buttons.
This is a screenshot of the app:
Here is code:
$(document).ready(function() {
$('#pdr_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('ajaxdata.getdata') }}",
"columns":[
{ "data": "checkbox", orderable:false, searchable:false},
{ "data": "ID_Piece" },
{ "data": "Designation" },
{ "data": "Status" },
{ "data": "action"}
],
//"order": [[ 0, "asc" ]],
'rowCallback': function(row, data, index){
if(data.Status == 'Disponible'){
$(row).find('td:eq(3)').css('background-color', 'green').css('color', 'white');
}
if(data.Status == 'Indisponible'){
$(row).find('td:eq(3)').css('background-color', 'red').css('color', 'white');
}
}
});
$(document).on('click', '.Ajouter_au_panier', function(){
$('#pdrModal').modal('show');
$('#pdr_form')[0].reset();
$('#form_output').html('');
$('#piece').text('PDR');
});
$(document).on('click', '.pdr_checkbox', function(){//How to color the entire line and get all the values of that line
});
$('#pdr_form').on('submit', function(event){//How to get all the values for the line of that button
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"{{ route('ajaxdata.postdata') }}",
method:"get",
data:form_data,
dataType:"json",
success:function(data)
{
if(data.error.length > 0)
{
var error_html = '';
for(var count = 0; count < data.error.length; count++)
{
error_html += '<div class="alert alert-danger">'+data.error[count]+'</div>';
}
$('#form_output').html(error_html);
}
else
{
$('#form_output').html(data.success);
$('#pdr_form')[0].reset();
$('#pdr_table').DataTable().ajax.reload();
}
}
})
});
Controller:
function getdata()
{
$pdrs = Pdrs::select('ID_Piece', 'Designation', 'Status');
return DataTables::of($pdrs)
->addColumn('checkbox', '<input type="checkbox" name="pdr_checkbox[]" class="pdr_checkbox" value="{{$ID_Piece}}" />')
->rawColumns(['checkbox','action'])
->addColumn('action', function($pdr){
return '<i class="glyphicon glyphicon-shopping-cart"></i> Ajouter au panier';})
->make(true);
}

You can use
select: {
style:'multi',
},
if you don't intend to use style:'multi'
use CTRL+Select for multiple selection under style:'os',
as given in the documentation in the link provided by you.
Check Here
Then, you can do a $.each on the selected checkboxes within the ajax click function and form the data variable that you want to submit to the controller.
Also, please follow the code of the documentation.
$('#someSubmitButton').on('submit', function(e){
//Place submit button within the form
var form = this;
//Define your dataTable to a variable - here it is table
var rows_selected = table.column(0).checkboxes.selected();
// Iterate over all selected checkboxes
$.each(rows_selected, function(index, rowId){.... Your other code goes
here based on how you want to handle.....}

Related

PHP: From ajax Items are not deleting when click on all delete checkbox

I am trying to delete all items when I check then select all checkbox, but it is deleting the single item.
Here is the code where I am getting all items id's on click on checkbox
$delete_vehicle_trim =Item::find($request->deletetrimid);
if ($delete_vehicle_trim != null) {
$delete_vehicle_trim->delete();
return response()->json(['msg'=>'Record Delete Successfully']);
}
else {
return response()->json(['msg'=>'Error In Delete']);
}
on ajax call trim = [] I am getting multiples id in this array
function viewtrim(id){
$('#select-all').click(function(event) {
var trim = [];
$.each($("input[name='checkbox']:checked"), function(){
trim.push($(this).val());
});
alert("Id is: " + trim.join(", "));
$('#select-all').on('click', function(e) {
var allVals = [];
$("checkbox:checked").each(function() {
id.push($(this).attr('data-id'));
});
});
$.ajax({
url : 'viewtrim/' +viewtrimid,
type : 'GET',
data : {
"_token": "{{ csrf_token() }}",
'viewtrimid': viewtrimid,
"_method": 'GET',
},
}
});
}
console.log($("input[name=checkbox]").val());
Any help?

"Add to cart" ajax button on DataTable

I am started to use DataTables because they provide what I need: ready to use pagination, ready to use how many items to show on the table 10, 25 .. etc. And here is the first problem. I want to put one button Add to cart at the end and with ajax to place items in basket which will downloaded later as zip. So far I was able to put the button but I'm very new in ajax and jquery stuff and can't figured out how to do the cart things. Here is what I have:
The table:
<table id="example" class="display table table-striped table-bordered responsive">
<thead>
<tr>
<th>№</th>
<th>Program</th>
<th>Title</th>
<th>Description</th>
<th>Add to Cart</th>
</tr>
</thead>
Here is how I put the custom button at the end
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "response.php",
"aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function (data, type, full) {
return 'Add to cart';
}
}]
});
});
How I trying to put them in the cart
$(document).ready(function(){
$.ajax({
type:'post',
url:'store_items.php',
data:{
total_cart_items:"totalitems"
},
success:function(response) {
document.getElementById("total_items").value=response;
}
});
});
function cart(id)
{
var ele=document.getElementById(upload_id);
var upload_title=document.getElementById("upload_title").value;
var upload_description=document.getElementById("upload_description").value;
$.ajax({
type:'post',
url:'store_items.php',
data:{
upload_title:upload_title,
upload_description:upload_description
},
success:function(response) {
document.getElementById("total_items").value=response;
}
});
}
function show_cart()
{
$.ajax({
type:'post',
url:'store_items.php',
data:{
showcart:"cart"
},
success:function(response) {
document.getElementById("mycart").innerHTML=response;
$("#mycart").slideToggle();
}
});
}
and the php part
session_start();
if(isset($_POST['total_cart_items']))
{
echo count($_SESSION['upload_title']);
exit();
}
if(isset($_POST['upload_title']))
{
$_SESSION['upload_title'][]=$_POST['upload_title'];
$_SESSION['upload_description'][]=$_POST['upload_description'];
echo count($_SESSION['upload_title']);
exit();
}
if(isset($_POST['showcart']))
{
for($i=0;$i<count($_SESSION['upload_title']);$i++)
{
echo "<div class='cart_items'>";
echo "<p>".$_SESSION['upload_title'][$i]."</p>";
echo "<p>".$_SESSION['upload_description'][$i]."</p>";
echo "</div>";
}
exit();
}
So far the main problem that I see is how to pass the ID of the item which I store in cart. On the datatable ID of the item is on the first №. Then I'm not sure how to pass it to the cart with this ajax.
If need I can show also the php part of response.php from where the table is populated.
For your MAJOR problem with getting ID you can make this:
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "response.php",
"aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function(data, type, full) {
return '<a class="btn btn-info btn-sm" href=#' + full[0] + '>' + 'Add to Cart' + '</a>';
}
}
}]
});
});
The mRender Function takes three parameters:
data = The data for this cell, as defined in mData
type = The datatype
(can be ignored mostly)
full = The full data array for this row.

ajax form validation in laravel 5

I am new in laravel and need help.
These are the values I'm getting via ajax, all values are to be stored in db, but how do I validate[check] if there are existing values or not before submitting a form using ajax?
$("#submit").click(function(e){
e.preventDefault();
var url = "{!! URL::to('/') !!}";
var id="{!! #$department->id !!}";
var token = "{!! csrf_token() !!}";
var customer_id = $("#customer_id").val();
var visiting_address1 = $("#visiting_address1").val();
var department_id = $("#department_id").val();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: url+"/customer/"+customer_id+"/popup_store",
data: { '_token':token, 'rest':'true', 'customer_id':$("#customer_id").val(), 'main_address':$("#main_address").val(),'visiting_city':$("#visiting_city").val(),'visiting_address':$("#visiting_address1").val(),'visiting_zip':$("#visiting_zip").val()},
async : false,
success : function(data) {
if(data == "success")
{
$("#addrecords").modal('hide');
}
else
alert(data);
}
});
});
First of all define you Jquery validation for you form like this:
$("#myForm").validate({
// Specify the validation rules
rules: {
name: "required",
},
// Specify the validation error messages
messages: {
name: "Please enter name",
},
submitHandler: function (form) {
// leave it blank here.
}
});
And then in your click button of submit button, write if condition to check validations:
$("#submit").click(function (e) {
if ($('#myForm').valid()) {
// your Ajax Call Code
} else {
return false;
}
});

AJAX with Multiple Submit

I currently have a 'Add to Cart' button which submits product data from an array and posts the data using AJAX.
Currently on submit only one of the three products are been send to the cart.
I was told to use .then function after each AJAX post but I'm unsure how to tie this in with the for() function and the array.
Any and all help would be very much appreciated! Thank you.
function addtocart() {
var products = [{
'id': 32,
'qty': 2
}, {
'id': 33,
'qty': 1
}, {
'id': 34,
'qty': 5
}];
$('.submit').on('click', function(e) {
e.preventDefault();
for (var j = 0; j < products.length; j++) {
jQuery.ajax({
type: 'POST',
url: 'XXX/?post_type=product&add-to-cart=' + products[j].id + '&quantity=' + products[j].qty
});
}
});
}
<div class="addtocart">
<button class="submit">Add to Cart</button>
</div>
Update:
function addtocart() {
var products = [{'product_id':32,'quantity':2},{'product_id':33,'quantity':1},{'product_id':34,'quantity':5}];
$('.submit').on('click', function(e){
e.preventDefault();
$.ajax(
{
type:'POST',
url:'XXX/?post_type=product&add-to-cart',
data:JSON.stringify(products)
}
);
console.log(JSON.stringify(products));
});
}
addtocart();
Network Snapshot
Console Log Snapshot
I was told to do something like this, but I can't add an ID without it been within a for()
url: 'XXX/?post_type=product&add-to-cart='+IDHERE

Calling ajax once

I have created a button on my website when it is clicked, I sent data on some php file using ajax and return the results. The code I am using is below,
My Goal :
When that button is clicked for the first time. I want to send the data on some php file using ajax and return the results, and
When it is clicked for the second time, I just want to hide the content, and
When it is clicked for the third time, I just want to show the container without calling the ajax again.
jQuery:
$(function() {
$('#click_me').click(function(){
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php",
}).done(function(data) {
$('#container').html(data);
}).success(function(){
$('#container').show('fast');
});
}else if(container == 'block'){
$('#container').hide('fast');
}
});
});
Html :
<input type="button" id="click_me" value="Click Me"/>
<div id="container"></div>
The jQuery way would be like this:
$(function() {
$('#click_me').one('click', function() {
$.ajax({
// ... other params ...,
success: function(result) {
$('#container').html(result).show('fast');
$('#click_me').click(function() {
$('#container').toggle('fast');
});
});
});
});
});
http://api.jquery.com/one/
http://api.jquery.com/toggle/
You can use the counter
http://forum.jquery.com/topic/making-a-number-counter
(function () {
var count = 0;
$('table').click(function () {
count += 1;
if (count == 2) {
// come code
}
});
})();
JQuery Mouse Click counter
Working Example of your code :-
http://jsfiddle.net/2aQ2g/68/
Something like this should do the trick...
$("#click_me").click(function(){
var $btn = $(this);
var count = ($btn.data("click_count") || 0) + 1;
$btn.data("click_count", count);
if ( count == 1 ) {
$.ajax({
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php"
})
}
else if ( count == 2 ) {
$('#container').hide('fast');
}
else {
$('#container').show('fast');
$btn.unbind("click");
}
return false;
});
One way to do it would be to add a class call count using jQuery every time the user clicks on the button (http://api.jquery.com/addClass/) and you can get the count value in the handler and based on that you can handle the click appropriately.
You can do this by defining a simple variable counting the clicks.
$(function() {
var clickCount = 1; //Start with first click
$('#click_me').click(function(){
switch(clickCount) {
case 1: //Code for the first click
// I am just pasting your code, if may have to change this
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php",
}).done(function(data) {
$('#container').html(data);
}).success(function(){
$('#container').show('fast');
});
}else if(container == 'block'){
$('#container').hide('fast');
}
break;
case 2:
//code for second click
break;
case 3:
//Code for the third click
break;
});
clickCount++; //Add to the click.
});

Categories