For load table data using ajax in table sorter i follow https://mottie.github.io/tablesorter/docs/example-pager-ajax.html
Load table data using ajax & mysql in tablesorter plugin
I would prefer to load first 25 record in table when page load . Does the tablesorter pager plugin support this? If so, what am I missing, because the documentation shows this example:i will try to load table data using table sorter.how i will set url
for page load event when i click on next button table record get
successfully.here i need to more setting for load table data when page
load.how i will set total rows ,how to set ajax url it`s not working properly
<?php echo $header; ?>
<script id="js">
$( document ).ready(function() {
// Initialize tablesorter
// ***********************
$("table")
.tablesorter({
theme: 'blue',
widthFixed: false,
sortLocaleCompare: true, // needed for accented characters in the data
sortList: [ [0,1] ],
widgets: ['zebra', 'resizable','filter']
})
// initialize the pager plugin
// ****************************
.tablesorterPager({
// **********************************
// Description of ALL pager options
// **********************************
// target the pager markup - see the HTML block below
container: $(".pager"),
ajaxUrl : '<?php echo SITE_URL."admin/index.php?route=technology/products/get_pro/"?>{page}?{filterList:filter}&{sortList:column}',
// use this option to manipulate and/or add additional parameters to the ajax url
customAjaxUrl: function(table, url) {
// manipulate the url string as you desire
// url += '&currPage=' + window.location.pathname;
// trigger a custom event; if you want
$(table).trigger('changingUrl', url);
// send the server the current page
return url;
},
ajaxError: null,
// add more ajax settings here
// see http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings
ajaxObject: {
type: 'GET', // default setting
dataType: 'json'
},
ajaxProcessing: function(data){
alert();
if (data && data.hasOwnProperty('rows')) {
var indx, r, row, c, d = data.rows,
// total number of rows (required)
total = data.total_rows,
// array of header names (optional)
headers = data.headers,
// cross-reference to match JSON key within data (no spaces)
headerXref = headers.join(',').replace(/\s+/g,'').split(','),
// all rows: array of arrays; each internal array has the table cell data for that row
rows = [],
// len should match pager set size (c.size)
len = d.length;
// this will depend on how the json is set up - see City0.json
// rows
for ( r=0; r < len; r++ ) {
row = []; // new row array
// cells
for ( c in d[r] ) {
if (typeof(c) === "string") {
// match the key with the header to get the proper column index
indx = $.inArray( c, headerXref );
// add each table cell data to row array
if (indx >= 0) {
row[indx] = d[r][c];
}
}
}
rows.push(row); // add new row array to rows array
}
// in version 2.10, you can optionally return $(rows) a set of table rows within a jQuery object
return [ total, rows, headers ];
}
},
// Set this option to false if your table data is preloaded into the table, but you are still using ajax
processAjaxOnInit: true,
// output string - default is '{page}/{totalPages}';
// possible variables: {size}, {page}, {totalPages}, {filteredPages}, {startRow}, {endRow}, {filteredRows} and {totalRows}
// also {page:input} & {startRow:input} will add a modifiable input in place of the value
output: '{startRow} to {endRow} ({totalRows})',
// call
initialRows: {
total: 100,
filtered: 1
},
// apply disabled classname (cssDisabled option) to the pager arrows when the rows
// are at either extreme is visible; default is true
updateArrows: true,
// starting page of the pager (zero based index)
page: 0,
// Number of visible rows - default is 10
size: 25,
// Saves the current pager page size and number (requires storage widget)
savePages: true,
// Saves tablesorter paging to custom key if defined.
// Key parameter name used by the $.tablesorter.storage function.
// Useful if you have multiple tables defined
storageKey: 'tablesorter-pager',
// Reset pager to this page after filtering; set to desired page number (zero-based index),
// or false to not change page at filter start
pageReset: 0,
// if true, the table will remain the same height no matter how many records are displayed.
// The space is made up by an empty table row set to a height to compensate; default is false
fixedHeight: false,
// remove rows from the table to speed up the sort of large tables.
// setting this to false, only hides the non-visible rows; needed if you plan to
// add/remove rows with the pager enabled.
removeRows: false,
// If true, child rows will be counted towards the pager set size
countChildRows: false,
// css class names of pager arrows
cssNext : '.next', // next page arrow
cssPrev : '.prev', // previous page arrow
cssFirst : '.first', // go to first page arrow
cssLast : '.last', // go to last page arrow
cssGoto : '.gotoPage', // page select dropdown - select dropdown that set the "page" option
cssPageDisplay : '.pagedisplay', // location of where the "output" is displayed
cssPageSize : '.pagesize', // page size selector - select dropdown that sets the "size" option
// class added to arrows when at the extremes; see the "updateArrows" option
// (i.e. prev/first arrows are "disabled" when on the first page)
cssDisabled : 'disabled', // Note there is no period "." in front of this class name
cssErrorRow : 'tablesorter-errorRow' // error information row
});
});
</script>
<section class="page-content">
<breadcrumbs-panel page-title="" class="breadcrumbs" id="menu"></breadcrumbs-panel>
<div class="module">
<div class="width100 gold-border-bottom">
<div class="floatleft">
<h1>View Products</h1>
</div>
</div>
<div class="margin-top10">
<table id="campanion-product" class="tablesorter display responsive">
<thead>
<tr>
<th>Product Name</th>
<th>Part Number</th>
<th>Product ID</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr >
<td data-value=">25"> 1</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<style>
.pager input.ts-startRow {
min-width: 30px;
}
</style>
<!--Pagination!-->
<div class="pager width100">
<img src="<?php echo HTTPS_PUBLIC; ?>images/tablesorter-first.png" class="first" alt="First" />
<img src="<?php echo HTTPS_PUBLIC; ?>images/tablesorter-prev.png" class="prev" alt="Prev" />
<!-- the "pagedisplay" can be any element, including an input -->
<span class="pagedisplay" data-pager-output-filtered="{startRow:input} – {endRow} / {filteredRows} of {totalRows} total rows"></span>
<img src="<?php echo HTTPS_PUBLIC; ?>images/tablesorter-next.png" class="next" alt="Next" />
<img src="<?php echo HTTPS_PUBLIC; ?>images/tablesorter-last.png" class="last" alt="Last" />
<select class="pagesize" title="Select page size">
<option value="25" selected="selected">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="500">500</option>
<option value="1000">1000</option>
<option id="allRowsTablePaginationOption" value="all">All Rows</option>
</select>
<!--<select class="gotoPage" title="Select page number"></select>-->
</div>
</div>
</div>
</section>
<?php echo $footer; ?>
I may be wrong, but from looking at the URL in the screenshot, there is a second ? which could be causing some trouble if not parsed correctly:
index.php?route=technology/products/get_pro/0?filter&column[0]=1
↑ ↑
The next page button may not be active (not seen in the screenshots) since the server is returning a total_rows value of 25, which equals the size setting. The pager code is assuming that all rows are showing; set this to the total number of entries in the database.
its because of widget i will set those are not working currently I need to kept only zebra widget which is the default & i also set wrong url prams i solved url issue using this url : stackoverflow.com/a/15303766/8064611
One More demo http://jsfiddle.net/Mottie/uwZc2/44/
$("table")
.tablesorter({
theme: 'blue',
widthFixed: false,
sortLocaleCompare: true, // needed for accented characters in the data
sortList: [ [0,1] ],
widgets: ['zebra']
})
Related
I want to input data from multiselect (right side) to database, I use the default form smart wizard from gentelella template, to get data from multiselect I make function:
function selectAll(theSel) {
var selLength = theSel.length;
for(i=selLength-1; i>=0; i--) {
theSel.options[i].selected = true;
}
}
I added this :
<form class="form-horizontal form-label-left" action="<?=site_url('index.php/biodata/commit'); ?>" method="POST" onsubmit="selectAll(document.getElementById('region_id_assign')); selectAll(document.getElementById('region_out_id_assign')); return;">
and change the code onfinish to true :
$.fn.smartWizard.defaults = {
selected: 0, // Selected Step, 0 = first step
keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled)
enableAllSteps: false,
transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft
contentURL:null, // content url, Enables Ajax content loading
contentCache:true, // cache step contents, if false content is fetched always from ajax url
cycleSteps: false, // cycle step navigation
enableFinishButton: false, // make finish button enabled always
hideButtonsOnDisabled: false, // when the previous/next/finish buttons are disabled, hide them instead?
errorSteps:[], // Array Steps with errors
labelNext:'Next',
labelPrevious:'Previous',
labelFinish:'Finish',
noForwardJumping: false,
onLeaveStep: null, // triggers when leaving a step
onShowStep: null, // triggers when showing a step
onFinish: true // triggers when Finish button is clicked
};
how to solve it so that the data into the database?
sorry, I'm new this time try using smart wizard
In my cart i have my products added, there are stored in sessions.
I want to store my selected option from all dropdown when the page is refreshed.
I need to refresh my page so my sessions can be updated so i can post in my database all the updated values.
What is wrong...
if i select an option for the first row of my product it saves in local storage.but when i select another product option from other row,it overwrites the local storage,so my local storage is saving only one option,and when selected other option from other products it is rewriting my only one save option in local storage.i have to save multiple option.
Without refresh what happens is...
lets say that i've selected 1 cushion in my gallery.
So in my cart this cushion will be 1 product, and if i add two more by clicking plus button and then click on confirm order,it will post in my DB the value of 1.
But not 3.
So my page needs to refresh, so for that i need to save all dropdown selection so i can refresh the page.
So far i tried to save it,but it saves the first row of my cart.
This is what i tried...
$(function() {
if (localStorage.getItem('fabric')) {
$(".fabric option").eq(localStorage.getItem('fabric')).prop('selected', true);
}
$(".fabric").on('change', function() {
localStorage.setItem('fabric', $('option:selected', this).index());
});
});
$(function() {
if (localStorage.getItem('size')) {
$(".size option").eq(localStorage.getItem('size')).prop('selected', true);
}
$(".size").on('change', function() {
localStorage.setItem('size', $('option:selected', this).index());
});
});
this is my foreach loop if needed to understand it better.
this script below is not important for this question,but it shows how i am handling my dropdowns to make ajax get values based on dropdown selection using data attribute.
script that gets cost and subtotal
Ok... Took a liitle time, but you will like my solution (I think).
We have to set storage row by row...
So an .each() loop has to be done on product rows.
We use the index of the .each() as a part of the storage name to ensure no overwriting.
Given this HTML that I made just for this example:
<div class="row">
<!-- other elements like img etc... -->
<select class="fabric">
<option>jeans</option>
<option>leather</option>
<option>cotton</option>
</select>
<select class="size">
<option>small</option>
<option>medium</option>
<option>large</option>
</select>
</div>
<div class="row">
<!-- other elements like img etc... -->
<select class="fabric">
<option>jeans</option>
<option>leather</option>
<option>cotton</option>
</select>
<select class="size">
<option>small</option>
<option>medium</option>
<option>large</option>
</select>
</div>
Here is the script:
$(function() {
$(".row").each(function(index){
// Fabric selection
if (localStorage.getItem('row_'+index+'_fabric')) {
$(this).find('.fabric option').prop('selected', false).eq(localStorage.getItem('row_'+index+'_fabric')).prop('selected', true);
console.log("Row#"+index+" get-fabric: "+localStorage.getItem('row_'+index+'_fabric'));
}
$(this).find(".fabric").on('change', function() {
localStorage.setItem('row_'+index+'_fabric', $(this).find('option:selected').index());
console.log("Row#"+index+" set-fabric: "+$(this).find('option:selected').index());
});
// Size selection
if (localStorage.getItem('row_'+index+'_size')) {
$(this).find('.size option').prop('selected', false).eq(localStorage.getItem('row_'+index+'_size')).prop('selected', true);
console.log("Row#"+index+" get-size: "+localStorage.getItem('row_'+index+'_size'));
}
$(this).find(".size").on('change', function() {
localStorage.setItem('row_'+index+'_size', $(this).find('option:selected').index());
console.log("Row#"+index+" set size: "+$(this).find('option:selected').index());
});
});
});
Try it on this CodePen!
(Change the selects and hit "Run" to refresh)
I have a invoice table and an invoice_item table. Each Invoice hasMany invoiceItem.
When creating an invoice the user is presented with a form with the invoice form fields and also a row with invoiceItem form fields.
What I want to do is to have a "add new item" link that dynamically (jQuery, AJAX) adds a new row of the item fields. User should be able to add as many rows as they want and each new row should appear below the last row.
Of course the row field attributes must also be correct so that the data can easily be inserted with the saveAll method.
What is the best and most proper way to accomplish this with CakePHP? I am using CakePHP 2.4.7.
Here's how I did it with data containing a hidden id, a label and an input field, all wrapped up in a fieldset. You could use actual tables to wrap it up.
Here's the generated HTML for two sets of fields and the link to click to add a row:
<fieldset>
<input type="hidden" name="data[VmfrDesignatedIncome][0][id]" value="668" id="VmfrDesignatedIncome0Id"/>
<div class="input text">
<label for="VmfrDesignatedIncome0Designation">Designation</label>
<input name="data[VmfrDesignatedIncome][0][designation]" value="blah" maxlength="512" type="text" id="VmfrDesignatedIncome0Designation"/></div>
</fieldset>
<fieldset>
<input type="hidden" name="data[VmfrDesignatedIncome][1][id]" value="669" id="VmfrDesignatedIncome1Id"/>
<div class="input text">
<label for="VmfrDesignatedIncome1Designation">Designation</label>
<input name="data[VmfrDesignatedIncome][1][designation]" value="blah2" maxlength="512" type="text" id="VmfrDesignatedIncome1Designation"/></div>
</fieldset>
Add row
and here's the Javascript which clones the last fieldset on the page, and then modifies the id, name and field values to increase the number in them by one. Note that the selectors have to accurately select each label or field using the > child selector.
/* As the strings to the function below may have [ or ]
** we want to stop it being treated as a regexp
*/
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};
function findNumberAddOne(attributeString) {
/*Finds the number in the given string
** and returns a string with that number increased by one
*/
var re = new RegExp("(.*)([0-9])(.*)");
var nPlusOne = attributeString.replace(re, "$2")+"+1";
var newstr = attributeString.replace(re, "$1")+eval(nPlusOne)+attributeString.replace(re, "$3");
return newstr;
}
$(document).ready(function() {
/* Duplicate the last set of designated income fields and increase the relevants id/name etc.
** so that it works as a new row in the table when saved*/
$('#addrow').click(function() {
$('fieldset:last').clone().insertAfter('fieldset:last');
$('fieldset:last > input').attr('id',findNumberAddOne($('fieldset:last > input').attr('id')));
$('fieldset:last > input').attr('value',''); /*Blank out the actual value*/
$('fieldset:last > input').attr('name',findNumberAddOne($('fieldset:last > input').attr('name')));
$('fieldset:last > div > label').attr('for',findNumberAddOne($('fieldset:last > div > label').attr('for')));
$('fieldset:last > div > input').attr('id',findNumberAddOne($('fieldset:last > div > input').attr('id')));
$('fieldset:last > div > input').attr('value',''); /*Blank out the actual value*/
$('fieldset:last > div > input').attr('name',findNumberAddOne($('fieldset:last > div > input').attr('name')));
});
});
Please check Dynamic form input fields in CakePHP tutorial. I used same for CakePHP 2.x and also for CakePHP 3.x. One problem in this tutorial is dynamic field ID creation. Each time it create same ID for same dynamic fields, like create GradeSubject for both Grade.0.subject and Grade.1.subject fields. If you need dynamic ID for each fields, you can modify this tutorial as like below.
According to tutorial just change View/Elements/grades.ctp content as:
<?php
$key = isset($key) ? $key : '{{ key }}';
// I changed <%= key %> to {{ key }}
?>
<tr>
<td>
<?php echo $this->Form->hidden("Grade.{$key}.id") ?>
<?php echo $this->Form->text("Grade.{$key}.subject",array("id"=>"Grade{$key}Subject")); ?>
</td>
<td>
<?php echo $this->Form->select("Grade.{$key}.grade", array(
'A+',
'A',
'B+',
'B',
'C+',
'C',
'D',
'E',
'F'
), array(
'empty' => '-- Select grade --',
"id"=>"Grade{$key}Grade"
)); ?>
</td>
<td class="actions">
Remove grade
</td>
</tr>
And also change your add.ctp javascript code as:
<script>
$(document).ready(function() {
//I changed undescore default template settings
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g
}
var
gradeTable = $('#grade-table'),
gradeBody = gradeTable.find('tbody'),
gradeTemplate = _.template($('#grade-template').remove().text()),
numberRows = gradeTable.find('tbody > tr').length;
gradeTable
.on('click', 'a.add', function(e) {
e.preventDefault();
$(gradeTemplate({key: numberRows++}))
.hide()
.appendTo(gradeBody)
.fadeIn('fast');
})
.on('click', 'a.remove', function(e) {
e.preventDefault();
$(this)
.closest('tr')
.fadeOut('fast', function() {
$(this).remove();
});
});
if (numberRows === 0) {
gradeTable.find('a.add').click();
}
});
</script>
the simplest idea got in my mind
1- make your items input with name array (<input type="text" name="items[]"/>)
2- create a button with class "addmore"
3- use jquery clone to duplicate the input on the click event on that button
I think this will help
i am trying to add / remove rows dynamically in / from a table using JQuery and the DataTables plugin, at a specific index.
$('#jt').dataTable();
The rows i try to add is some additional info, which i get by clicking on a row (ajax). Each row has a unique id that i pass as an argument.
$('#jt').on('click','.togetinfo',function() {....
$.get(functions, { id: id }).done(function(data) {
....
For each result i add the content to a var and add it after the row i want.
$.each(jsonresult, function(i,item){
subentries = subentries + ....... /* the info */
});
$('#jt > tbody > tr').eq(id).after(subentries);
This works perfectly on the first page, but on the second page of the entries (paging) it does not insert the new data.
The fnAddData() of the "DataTables" API inserts the data on the end of the entire table.
Does anyone has an idea of how to make it work on all the pages?
The false was found in the indexes of each row after the first page.
Each index (on click) must be recalculated.
var rowIndex = oTable.fnGetPosition( $(this).closest('tr')[0] );
rowIndex = rowIndex - oSettings._iDisplayStart;
I am using jquery star rating plugin "Raty" https://github.com/wbotelhos/raty.
i am generating a result set from database with PHP. that includes score also. I want set score property for every individual rating component. how can I do that?
I am using this syntax for showing the stars.
$('.stars_small').raty({
readOnly : true,
half : true,
score : 2,
space : false
});
<div class="stars_small"></div>
there are many div in a single page with the class "stars_small" generated dynamically. I want to set "score" for every div.
$('.stars_small').raty({
readOnly : true,
half : true,
score: function() {
return $(this).attr('data-rating');
}
space : false
});
this worked fine for me.
the plugin is adding a hidden textbox in every div with class="stars_small"
like this
<div class="stars_small">
<input type="hidden" name="score" value="3.5" readonly="readonly">
</div>
So I just set the value attribute with number coming from database query.
Try this
$('.stars_small').each(function() {
$(this).raty({
readOnly : true,
half : true,
score : 2,
space : false
});
});
Assuming that you have generated with PHP the JS lines:
// lines of JS generated with a loop in PHP (for the rate content)
var rates = [];
rates.push({...one rate coming from PHP...});
rates.push({...one rate coming from PHP...});
// etc...
You can run you rating star with :
$(document).ready(function() {
$(".starts_small").each(function(index, element) {
$(this).raty(rates[index]);
});
});
Here is what i did:
I created a separate class for each of those star divs:
<div class="star s0"></div>
<div class="star s1"></div>
<div class="star s2"></div>
I also generate the array of values in my template (that is, pass the values from my server-side script to the web page). Like so:
var array = new Array(2.4, 2.9, 5.0);
And then I declare the thing common for all the three "star banners" in the $(".star") call, and set the values in a cycle:
$('.star').raty({
half : true
});
for (i = 0; i < array.length; i++) {
$('.s' + i).raty({
score:array[i]
});
}
For V.2.7 Jquery raty is the form:
If you need to start you score depending of a dynamic value, you can to use callback for it.
You can pass any value for it, not necessarily a data- value. You can use a field value for example.
<div data-score="1"></div>
$('div').raty({
score: function() {
return $(this).attr('data-score');
}
});