"Add to cart" ajax button on DataTable - php

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.

Related

Can't attach data to select2 option

I want to make edit form and attach data from database to select2 option. In insert form this select2 option search data in database when we type word by word. I can't attach the data in this select2 option. I want to make this select2 option is fill with the data from database and also can change the data like in insert form. I already try $('#requestor').val($row['requestor']); but the data doesn't appear. Can anyone help me???
<select class="requestor form-control" name="requestor" id="requestor" style="width:700px" required="required">
<option value=""></option>
</select>
//search data in database word by word
$('.requestor').select2({
placeholder: 'Requestor Name',
ajax:{
url: "<?php echo base_url('Hire_4/select_personnel'); ?>",
dataType: "json",
delay: 250,
processResults: function(data){
var results = [];
$.each(data, function(index, item){
results.push({
id: item.ID,
text: item.FullName,
option_value:item.ID
});
});
return{
results: results,
cache: true,
};
},
}
});
function load() {
alert('ok');
//console.log(<?php echo $row['ID']; ?>);
if (<?php echo $row['ID']; ?> != '') {
$('#requestor').val($row['requestor']);
}
}
window.onload = load;
Thank You :)
Your code is very messy. Be more clear like this:
<div class="col-md-12">
<select style="width:100%;" name="requestor[]" id="requestor" class="select2-multiple" multiple></select>
</div>
Then:
var $ajax = $("#requestor");
$ajax.select2({
ajax: {
url: "<?php echo base_url('Hire_4/select_personnel'); ?>",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return{
search: params.term
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data
};
},
cache: true
},
language: "en",
placeholder: "Requestor Name",
allowClear: true,
minimumInputLength: 3,
maximumSelectionLength: 1,
escapeMarkup: function (markup) { return markup; },
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo(repo) {
var markup = repo.text ;
return markup;
}
function formatRepoSelection (repo) {
return repo.Name.replace(/<\/?("[^"]*"|'[^']*'|[^>])*(>|$)/g, "");
}
Your Ajax data must be have this format:
data[0]['ID'] = 1; //You must have "ID" key
data[0]['Name'] = 'Name'; //You must have "Name" key
It's easy that's it!
Good luck.

How to send ajax request in Datatables in Codeigniter

I Have used this ignited_datatables https://github.com/IgnitedDatatables/Ignited-Datatables in my CodeIgniter project. It successfully returns data from the database. But the main problem is that when I add a new record the newly inserted data is not shown in the table automatically and when I refresh the page then the newly inserted data is then shown in the table. so I want to show that data automatically through ajax and I have not to refresh the page.
My View
<div class="box-body table-responsive">
<table id="Slider_table" class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>item_Price</th>
<th>Description</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div><!-- /.box-body -->
This Script is Inside the View
$(document).ready(function() {
$("#Slider_table").dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxDataProp": "data",
"fnServerData": function(sSource, aoData, fnCallback){
$.ajax({
"dataType": "json",
"type" : "POST",
"url" : "'.base_url().'Home/items_list/list",
"data" : aoData,
"success" : function(res){
fnCallback(res);
}
});
}
});
});
I think you need to use draw() method after success in order to have the table's display updated.
table.row.add( {
//you dynamic data
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
} ).draw();
as per documentation. please refer draw()
You can use ajax.reload() method
var i=1;
function datatable()
{
$("#myTable1").dataTable().fnDestroy();
$('#myTable1').DataTable({
"ordering": true,
"searching": true,
"bPaginate": true,
ajax: 'myajaxURL.php',
columns : [
{ "render": function ( data, type, full, meta ) { return i++; }
},
{"data": "col1"},
{"data": "col2"},
{"data": "col3"},
]
});
}
function insertData {
//after each insertion do this
var i=1;
$('#myTable1').DataTable().ajax.reload();
//after each insertion do this
}
$(document).ready(function () {
datatable();
});
i always did this in every view of my page
var table;
table = $('#Slider_table').dataTable({
"bPaginate": false,
"bLengthChange": false,
"bFilter": false, // OPTIONAL
"bSorting": false,
"bInfo": true,
"bAutoWidth": false,
});
function getData() {
$.ajax({
type: "POST",
url: "<?php echo base_url('your_controler/function_name'); ?>",
data: aoData,
error: function(response) {
alert('Error')
},
success: function(response) {
setTable(response);
}
});
}
function setTable(response) {
var obj = JSON.parse(response);
var t = $('#Slider_table').dataTable();
t.clear().draw();
$.each(obj, function(index, value) {
var a = value.a;
var b = value.b;
var c = value.c;
t.row.add([
a,
b,
c
]).draw(false);
})
}
So everytime you reload or insert a new data,you just have to call getData() function to load a new set of data you just insert. And t.clear().draw(); will clear all data from tbody,and replaced it with new one . Hope this helps

Laravel DataTables multiple select with checkboxes

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.....}

Load dataTable. Successful AJAX request, but no data visible

How do I load json data with serverside processing in a dataTable?
I'm trying to build a custom Wordpress plugin and display results from wpdb inside a dataTable.
I get a successful AJAX return call, but the dataTable only shows a "Processing..." stage and the table does not fill the rows (keeps empty).
Although I have read many(!) similar problems and answers here, any help to load data with ajax and json_encode is much appreciated.
The current code:
dahsboard.php
<table id="table-id" cellpadding="1" cellspacing="1" width="100%">
<thead><tr>
<th>h_id</th>
<th>h_subject</th>
</tr></thead>
ajax-grid-data.php
add_action('wp_ajax_my_action', 'my_action_callback');
function my_action_callback(){
global $wpdb;
$query = "SELECT h_id, h_subject FROM wp_tablename ORDER BY h_id limit 3";
$myrows = $wpdb->get_results($query);
foreach ($myrows as $value) {
$ResultData['h_id'] = $value->h_id;
$ResultData['h_subject'] = $value->h_subject;
$data[] = $ResultData;
}
$json_data = array(
"draw" => 1,
"recordsTotal" => 3,
"recordsFiltered" => 3,
"data" => $data,
);
echo json_encode($json_data);
die();
}
I think that the problem is in datatype formatting underneath:
dashbboard.js
var oTable;
jQuery(document).ready(function() {
jQuery.fn.dataTable.ext.errMode = 'throw';
oTable = jQuery('#table-id').DataTable( {
"serverSide": true,
"processing": true,
"columnDefs": [{"defaultContent": "-","targets": "_all"}],
"columns": [
{ "data": "h_id" } ,
{ "data": "h_subject" }
],
"ajax":{
url: "admin-ajax.php?action=my_action",
type: "post",
dataSrc:'',
dataType : "json",
contentType: "application/json; charset=utf-8",
//dataSrc: function(data){ return data.data; },
//async : false,
//processData: true,
//accepts: {json: "application/json, text/javascript"},
success: function(data){
console.log(JSON.stringify(data)); // successful echo data objects are shown in dashboard.
},
error: function(){
jQuery("#tablename").append('<tbody class="grid-error"><tr><th colspan="2">No results.</th></tr></tbody>');
jQuery("#tablename_processing").css("display","none");
}
},
});
});
Current results
Result php file test: .../wp-admin/admin-ajax.php?action=my_action
{"draw":1,"recordsTotal":3,"recordsFiltered":3,"data":[{"h_id":"37168","h_subject":"6216"},{"h_id":"37169","h_subject":"7021"},{"h_id":"37170","h_subject":"8923"}]}
Result ajax success function, console data:
{"draw":1,"recordsTotal":3,"recordsFiltered":3,"data":[{"h_id":"37168","h_subject":"6216"},{"h_id":"37169","h_subject":"7021"},{"h_id":"37170","h_subject":"8923"}]}
Result dashboard table only shows: processing...
Deleting the dataSrc and success function did wonders and fills up the dataTable with data. I really appreciate the help and efforts of #bassxzero and #davidkonrad.
Ensuring that there is an answer, "on behalf of" the new version of dashboard.js:
var oTable;
jQuery(document).ready(function() {
jQuery.fn.dataTable.ext.errMode = 'throw';
oTable = jQuery('#table-id').DataTable( {
"serverSide": true,
"processing": true,
"columnDefs": [{"defaultContent": "-","targets": "_all"}],
"columns": [
{ "data": "h_id" } ,
{ "data": "h_subject" }
],
"ajax":{
url: "admin-ajax.php?action=my_action",
type: "post",
dataType : "json",
contentType: "application/json; charset=utf-8",
error: function(){
jQuery("#tablename").append('<tbody class="grid-error"><tr><th colspan="2">No results.</th></tr></tbody>');
jQuery("#tablename_processing").css("display","none");
}
},
});
});

kendoui Grid with autocomplete on its toolbar?

Update:
I tried and spent alot of my time fixing the issue, and at last problem solved.
But initially Many Thanks to OnaBai and to my colleague who helped to come this far.
Now i am stuck here.
I type username and it show display on dropdown and after pressing TAB or ENTER it show the result in grid.
The result is only shown in grid if it is from page "1", but if it is from page "2" or any other further page the result is not shown.
Here is how it is working:
but when if i search for other user which is not on page 1 then it dont show display the other user in grid. instead i get empty grid.
FireBug screenShots:
Here is my Updated Code after i did some more changes in the code.:
<?php
/*foreach($users_list_data->result() as $row){
echo $row->Username."<br />";
}*/
?>
<div id="grid"></div>
<div id="details" />
<div class="second_column_content_container">
</div>
<script>
function create_user() {
var entryform = $("#insert_user_info");
$.ajax({
type : 'POST',
url : '<?php echo base_url(); ?>/index.php/user_management/manage_users/createUser',
data : entryform.serialize(),
success : function(response) {
$(".second_column").html(response);
}
});
}
function create_user_form() {
$.ajax({
type : 'POST',
url : '<?php echo base_url(); ?>/index.php/user_management/manage_users/load_user_form',
success : function(response) {
$(".second_column").html(response);
}
});
}
function onChange(arg) {
var selected = "";
var grid = this;
grid.select().each(function() {
var dataItem = grid.dataItem($(this));
selected = dataItem.Username;
});
$.ajax({
type: "POST",
url: "<?php echo base_url()?>index.php/user_management/manage_users/get_user_groups/"+selected,
beforeSend: function(){
$("#pre_image").attr("src","http://localhost/zorkif_new/images/pre.gif");
},
success: function(output_string) {
$('.data_column_a').html(output_string);
}
});
}
var wnd, detailsTemplate;
$(document).ready(function(){
var serverBaseUrl = "<?php echo base_url(); ?>";
$("#grid").kendoGrid({
dataSource:{
serverPaging: true,
transport: {
read: serverBaseUrl + "index.php/user_management/manage_users/list_view/",
update: {
url: serverBaseUrl + "index.php/user_management/manage_users/userUpdate/",
type: "POST"
}
// destroy: {
// url: serverBaseUrl + "index.php/user_management/manage_users/userDelete/",
// dataType: "jsonp"
// }
//update: "<?php echo base_url() ?>index.php/user_management/manage_users/list_view/"
},
error: function(e) {
alert(e.responseText);
},
schema:{
data: "data",
total: "total",
model: {
id: "UserID",
fields: {
FirstName: { editable: true },
LastName: { validation: { required: true} },
MiddleNames:{validation:{required:true}}
}
}
},
pageSize:5
},
toolbar: kendo.template($("#toolbarTemplate").html()),
scrollable: true,
selectable: "row",
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false
},
columns: [
{
field: "UserID",
hidden:true
},
{
field: "Username",
title:"Username"
},
{ field: "FirstName",
title:"First Name"
},
{field:"MiddleNames"},
{field:"LastName"},
{field:"City"},
{field:"Email"},
//{field:"Actions"},
//{command: { text: "Delete", click: showDetails }, title: " ", width: "140px"},
{command: { text: "Details", click: redirectToPage }, title: " ", width: "140px" },
{ command: { text: "Edit", click: redirectToEditPage }, title: " ", width: "140px" }
],
change: onChange,
editable: "popup"
});
$("#users").kendoAutoComplete({
minLength: 3,
dataTextField: "Username",
dataSource: {
serverFiltering: true,
transport: {
read: {
type: "GET",
dataType: "json",
contentType:'application/json; charset=utf-8',
url: serverBaseUrl + "index.php/user_management/manage_users/search_user/",
data: function (arg){
//alert(arg);
//alert({Username:autocompleteUsers.data("kendoAutoComplete").value});
return {Username : $("#users").data("kendoAutoComplete").value()};
//return $("#users").data("kendoAutoComplete").value();
}
}
}
},
change: onChangeAutoComplete
});
function onChangeAutoComplete(){
var value = this.value();
var grid = $('#grid');
if (value) {
grid.data("kendoGrid").dataSource.filter({ field: "Username", operator: "Contains", value: value });
} else {
grid.data("kendoGrid").dataSource.filter({});
}
}
/*$("#users").kendoAutoComplete({
minLength: 3,
dataTextField: "Title",
//JSON property name to use
dataSource: {
pageSize: 10,
//Limits result set
transport: {
read: {
url: "/echo/json/",
//using jsfiddle echo service to simulate JSON endpoint
dataType: "json",
type: "POST",
data: {
// /echo/json/ echoes the JSON which you pass as an argument
json: JSON.stringify([
{
"Title": "Doctor Who: The Trial of a Time Lord"},
{
"Title": "Doctor Who: The Key to Time"},
{
"Title": "Doctor Who: The Time Meddler"},
{
"Title": "Doctor Who: The End of Time"}
])
}
}
}
}
});*/
/*change: function () {
var value = this.value();
if (value) {
grid.data("kendoGrid").dataSource.filter({ field: "UserID", operator: "eq", value: value });
} else {
grid.data("kendoGrid").dataSource.filter({});
}
}
});*/
/*$("#users").blur(function() {
var data = $(this).data("kendoAutoComplete").dataSource._data,
nbData = data.length,
found = false;
for(var iData = 0; iData < nbData; iData++) {
if(this.value === data[iData].Title)
found = true;
}
console.log(found);
});*/
wnd = $("#details").kendoWindow({
title: "Customer Details",
modal: true,
visible: false,
resizable: false,
width: 300
}).data("kendoWindow");
detailsTemplate = kendo.template($("#template").html());
});
function redirectToPage(e){
e.preventDefault();
var row = $(e.target).closest("tr");
var item = $("#grid").data("kendoGrid").dataItem(row);
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/user_management/manage_users/ViewProfile/'?>"+JSON.parse(item.UserID),
success: function(output_string){
$('.second_column_content_container').html(output_string);
//$('.second_column_content_container').innerHTML("hello");
//alert(output_string);
},
error: function(data){
alert("error");
}
});
}
function redirectToEditPage(e){
e.preventDefault();
var row = $(e.target).closest("tr");
var item = $("#grid").data("kendoGrid").dataItem(row);
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/user_management/manage_users/edit_user/'?>"+JSON.parse(item.UserID),
success: function(output_string){
$('.second_column_content_container').html(output_string);
//$('.second_column_content_container').innerHTML("hello");
//alert(output_string);
},
error: function(data){
alert("error");
}
});
}
//show details on a popup
function showDetailsPopup(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
}
//This will redirect to Next Page
function showDetails(e) {
e.preventDefault();
var row = $(e.target).closest("tr");
var item = $("#grid").data("kendoGrid").dataItem(row);
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/user_management/manage_users/list_view/'?>"+JSON.parse(item.UserID),
success: function(data){
alert("done");
//$('.second_column_content_container').html(output_string);
//$('.second_column_content_container').innerHTML("hello");
//alert(output_string);
},
error: function(data){
alert("error");
}
});
//var grid = $("#grid").data("kendoGrid");
//alert(JSON.parse(item.UserID));
//window.location.href="http://www.google.com/";
}
</script>
<script type="text/x-kendo-template" id="template">
<div id="details-container">
<h2>#= FirstName #</h2>
<h2>City: #= City # </h2>
</div>
</script>
<script type="text/x-kendo-template" id="toolbarTemplate">
<div class="toolbar">
<label class="category-label" for="users">Search Users: </label>
<input type="text" id="users" style="width: 250px;" />
</div>
</script>
<div class="data_column_a">
<img src="" id="pre_image" >
</div>
Now how to solve this very extremely difficult problem O_o??
Update:
This Username is on Page 2 of the Grid as can be seen in ScreenShot.
But during Search, it sends the headers of page 1 when i search for username that is other than of page 1.
Banging my head to walls, How to Solve ?
The problem seems to be related to you autocomplete definition that is not sending any Username argument on read. Try defining transport.read as:
transport : {
read : {
url : "search_user.php",
data: function (arg) {
return {Username : autocompleteUsers.data("kendoAutoComplete").value()};
}
},
dataType: "json",
type : "POST"
},
EDIT: For applying selected value on autocomplete as filtering condition for the grid. You should do:
var autocompleteUsers = $("#users").kendoAutoComplete({
dataTextField: "Username",
dataSource : {
severFiltering: true,
transport : {
read : {
url : "search_user.php",
data: function (arg) {
return {Username: autocompleteUsers.data("kendoAutoComplete").value()};
}
},
dataType: "json",
type : "POST"
}
},
change : function () {
var username = autocompleteUsers.data("kendoAutoComplete").value();
var filter = {
logic : "and",
filters: [
{
ignoreCase: true,
field : "Username",
value : username,
operator : "startswith"
}
]
};
$("#grid").data("kendoGrid").dataSource.filter(filter);
}
});

Categories