Hi have an api made with Laravel. This api will return the paginatted records of data. So it will include the data, count, total, hasMorePages and currentPage. I am retur
How do I customize the pagination links in the DataTable? Also, I want to put a callback ajax function to fetch the next page. I checked the documentation https://datatables.net/reference/option/serverSide
But I cannot find what I need to match my requirements. Here's my javascript:
$("#search_games").click(function(){
var from = $("#from_date").val();
var to = $("#to_date").val();
console.log(from);
console.log(to);
$.post("/api/v1/get_games_result", { from: from, to: to }, function (data) {
if ( ! $.fn.DataTable.isDataTable( '#example' ) ) {
var t = $('#example').DataTable();
t.clear().draw();
var count = data.count;
var currentPage = data.currentPage;
var hasMorePages = data.hasMorePages;
var total = data.total;
var records = data.data;
console.log(records.length);
$.each(records, function (key, value) {
var game_data = value.game_data;
t.row.add( [
game_data.game_id,
game_data.game_date+" "+game_data.game_time,
game_data.game_closing
] ).draw( false );
});
}
var info = t.page.info();
console.log(data);
});
});
I want to make a function that when user clicked the pagination page button, I will request for the next page:
I think that you get the ID of Next link.
Then add the click event in the IF clause:
if ( ! $.fn.DataTable.isDataTable( '#example' ) ) {
<....>
$('#ID of Next link').click(function() {
Repost JSON Code here;
});
}
Related
I'm trying to build a product compare module with a bootstrap 4 dropdown.
Inside that dropdown there are products listed with some info. When you click delete at a product then a function called updateCompareis loaded. This function loads json data and updates the compare list. This all works fine except when there's only one product listed. When I click delete on the last item then the function throw errors.
So what I have is this:
function updateCompare(){
$.get(compareUrl + '?format=json', function(e) {
products = [];
$.each(e.compare.products, function(index, product) {
// ... code to build products ....
products.push(productHtml);
});
products.join('');
$('#compare .compare-inner .empty').html(products);
})
}
$(function(){
// delete product from compare
$(document).on("click", "#compare .remove", function(e) {
e.preventDefault();
var vid = $(this).closest('.item').data('vid');
var url = compareUrl + 'delete/' + vid;
$.ajax({
type: "POST",
url: url,
success: function(msg){
updateCompare()
}
});
});
});
The error I get is TypeError: a is undefined
What I tried in updateCompare is things like:
function updateCompare(){
$.get(compareUrl + '?format=json', function(e) {
products = [];
if(e.compare.products.length > 1 ){
$.each(e.compare.products, function(index, product) {
// .... code to build products
});
} else {
$('#compare').dropdown("dispose")
}
But above throws an error like: TypeError: e.compare.products is undefined
Also I tried:
if(e.compare.products.length > 1 || e.compare.products != NULL || e.compare.products != false ){
But that throws an error e.compare.products is undefined.
I've been working on this way too long so perhaps I miss something very simple. I just can't see it anymore :(
Any help greatly appreciated!!
As per request
Empty compare json:
{
"compare":false
}
JSON with 3 products:
{
"compare":{
"products":[
{
"id":39687158,
},
{
"id":39687161,
},
{
"id":39687164,
}
]
},
}
Contacts are created dynamically (added or deleted). For each contact created, a country must be selected and the provinces for that country must be loaded via ajax.
Parent element
#contacts
Child elements
#contacts_0_country
#contacts_0_provinces
#contacts_1_country
#contacts_1_provinces
etc
Everything works perfectly except that i have to switch the country selection twice for the ajax to take charge and change the provinces for the country selected
This problem is due to below js but i cant find it:
(function ( $ ) {
'use strict';
$(document).ready(function() {
$('#contacts').on("change", [$('select')],function() {
$("select[id^='contacts'][id$='_country']").each(function() {
var id = parseInt(this.id.match(/\d+/), 10);
var $country = $("#contacts_" + id + "_country");
var $province = $("#contacts_" + id + "_provinces");
// When country gets selected ...
$country.on('change',["#contacts_" + id + "_country"], function () {
// ... retrieve the corresponding form
var $form = $(this).closest('form');
// Simulate form data, but only include the selected value
var data = {};
data[$country.attr('name')] = $country.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) {
// Replace current province field ...
$("#contacts_" + id + "_provinces").replaceWith(
// ... with the returned one from the AJAX response
$(html).find("#contacts_" + id + "_provinces")
);
// Province field now displays the appropriate provinces
}
});
});
});
});
});
})( jQuery );
I found an answer to my own question. Below is now working perfectly. Provinces are populated for the relevant country selected and this also works on new contacts added dynamically on the collection
(function ( $ ) {
'use strict';
$(window).load(function() {
$('#contacts').on("click", [$('select')], function(event) {
var $id = event.target.id;
var id = parseInt($id.match(/\d+/), 10);
var $country = ('#' + $id);
var $country = $($country);
var $form = $country.closest('form');
// Simulate form data, but only include the selected value
var data = {};
data[$country.attr('name')] = $country.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) {
// Replace current province field ...
$("#contacts" + id + "_provinces").replaceWith(
// ... with the returned one from the AJAX response
$(html).find("#contacts" + id + "_provinces")
);
// Province field now displays the appropriate provinces
}
});
//});
});
});
})( jQuery );
I hope it helps someone!
I'm not good in JavaScript and I wish someone could help.
The issue is this:
$(function(){
$('.preview-add-button').click(function(){
var form_data = {};
form_data["concept"] = "café Noir";
form_data["status"] = parseFloat(10).toFixed(2);
form_data["description"] = 1;
form_data["amount"] = parseFloat(10 * form_data["description"]).toFixed(2);
form_data["remove-row"] = '<span class="glyphicon glyphicon-remove"></span>';
var row = $('<tr></tr>');
$.each(form_data, function( type, value ) {
$('<td class="input-'+type+'"></td>').html(value).appendTo(row);
});
$('.preview-table > tbody:last').append(row);
calc_total();
});
The JavaScript works perfectly but I need to send the table to a php so that it can be stored in database.
The complete source code is from bootsnipp.
Modify to your taste and add this to your code
$.post('your_post_url',
{
data: value,
data: value
},
function(data)
{
//what to do when ajax request completes
})
I am using Jtable for booking events. In combination with PHP, MySQL. My question is, is there a way to just reload every 10 second single column. Precisely I have something like this:
Checkbox ID Event Reservations
+ 4 ev1 22
- 5 ev2 19
I would like to have the reservations column reloaded every 10 seconds, so the user that is logged in can see the changes. Now I got it working with reloading the whole table, but this is not what I really need because every user can book only 9 events and I need to have checkboxes at the left side. After reloading the whole table my checkboxes are not working as expected. So is there a way to reload just one column? My code right now is:
window.setInterval(function(){
$('#Events').jtable('reload');
}, 10000);
Any help or suggestion would be appreciated.
I found a way around how to solve it:
First create a new field in JS like this:
test: {
title: 'test',
display: function (data) {
var $div = $('<div id="test"">'+data.record.id+'</div>');
return $div;
}
},
Than create a function that will be run every 10 seconds and make an AJAX request:
function UpdateRes(){
$.ajax({
url: 'Actions.php?action=update',
type: 'post',
data: '&kiu='+$kiu,
}).success(function(data) {
var jsondata = JSON.parse(data);
$.each(jsondata.Records, function(i, item) {
$('.jtable tr.jtable-data-row').each(function(){
if($(this).attr('data-record-key')==item.id){
$(this).find('div').html( item.reservations );
}
})
});
});
}
window.setInterval(function(){
UpdateRes();
}, 10000);
Let your JSON response look like this:
{"Result":"OK",
"Records":
[
{"0":"111","id":"111","1":"20","reservations":"20"},
{"0":"127","id":"127","1":"20","reservations":"20"},
{"0":"133","id":"133","1":"20","reservations":"20"},
{"0":"134","id":"134","1":"20","reservations":"20"},
{"0":"135","id":"135","1":"20","reservations":"20"},
{"0":"326","id":"326","1":"20","reservations":"20"}
]}
And in the end in Actions.php make your query in try catch:
else if($_GET["action"] == "update")
{
//Get records from database
$result8 = mysqli_query($con,
"SELECT l.id,(l.max-l.reserviert) as reservations
FROM td_res l WHERE
l.kiu='" . mysqli_real_escape_string($con,$_POST["kiu"]) . "';");
//Add all records to an array
$rows8 = array();
while($row8 = mysqli_fetch_array($result8))
{
$rows8[] = $row8;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows8;
print json_encode($jTableResult);
}
I tried to create a jquery plugIn that load multiple feed rss (they are flexible can be 1 or 2 or 3 ect...), for create an html that show the news feed loaded. My target is having the possibility to load multiple rss feed (xml) and display them by html. When I tried seem that the callback is overwrite,I received 2 results but equal.
Example:
(function($){
$.fn.getFeed = function(Obj){
var
arrOpt = Obj.arrayOptions,
arrOptLng = arrOpt.length;
for(var i = 0; i < arrOptLng; i++){
var
index = i,
Opt = arrOpt[i],
feedUrl = Opt.feed,
sucFnc = Opt.callback,
$cnt = this;
console.log(index);
// here:
// 0
// 1
$.ajax({
url:feedUrl,
dataType: "jsonp",
success:function(data){
sucFnc(data,$cnt,Opt,index);
},
error:function(){
$cnt.html('error');
}
});
}
}
})(jQuery);
function feedManipulation(){
console.log(index)
// here:
// 1
// 1
}
/* DOM LOADED */
$(function(){
$('.news').getFeed({ // Activation getFeed
arrayOptions:[{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
},{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
}]
});
});
Ciao, I wrote this question and I created the solution so I would explain.
In this code I removed the cyclo for and I create a function that contain the ajax call.
The first time that I trigger the ajax function I pass an argument to the ajax function with inside an object that I used to set the plugIn (lock on the bottom) whereas my ajax function is itself calls, before sending the same object to the ajax function I change some information like "Opt.index" creating in this way a ajax cyclo. Is it really usefull ;) use it.
(function($){
$.fn.getFeed = function(Obj){
// Options object
Opt = new Object();
Opt.index = 0;
Opt.$cnt = this;
Opt.arrOpts = Obj.arrayOptions;
Opt.arrOptLng = Opt.arrOpts.length;
Opt.arrOpt = Opt.arrOpts[Opt.index];
Opt.feedUrl = Opt.arrOpts[Opt.index].feedUrl;
// ajax call
cycloAjax(Opt);
}
/* ajax cyclo */
function cycloAjax(Obj){
$.ajax({
url: Obj.feedUrl,
dataType: "jsonp",
success:function(data){
feedManipulation(data,Obj.$cnt,Obj);
if(Obj.index < Obj.arrOptLng - 1){
Obj.index++;
Obj.arrOpt = Obj.arrOpts[Obj.index];
Obj.feedUrl = Obj.arrOpts[Obj.index].feedUrl;
cycloAjax(Obj);
}
else{
completeLoadFeeds(Obj.$cnt,Obj);
}
},
error:function(){
Obj.$cnt.html('<p>error</p>');
}
});
}
.
.
.
})(jQuery);
/* DOM LOADED */
$(function(){
$('.news').getFeed({ // Activation getFeed
arrayOptions:[{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
},{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
}]
});
});