i have a datatable for which my jquery is as follows,
$('#example').DataTable({
"lengthMenu": [[10,15,20,25,-1], [10,15,20,25,'All']],
"processing": true,
"serverSide": true,
ajax: {
url: 'url2',
dataSrc: 'data'
},
columns: [
{ data: 'column1' },
{ data: 'column2' },
{ data: 'column3' },
{ data: 'column4' },
{ data: 'column5' },
{ data: 'column6' }
]
});
this is working properly. The only issue is although its showing pagination links, they are not clickable and all the rows are displayed in first page itself.
for eg. if there are 100 rows, the links are getting generated 1-10 but all the 100 records are showing on the first page itself.
I've referred ,
https://datatables.net/examples/data_sources/server_side
what am i doing wrong here?
Thank you for your suggestions
Server side code -
$total_records = $this->model2->getTotal();
$query['results'] = $this->model1->get_Data();
$data = array('data' => $query['results'],
"draw" => (isset($_REQUEST["draw"]) ? $_REQUEST["draw"] : 0),
"recordsTotal" => $total_records,
"recordsFiltered" => $total_records
);
echo json_encode($data);
I think i know what am i doing wrong,
when i print $_GET in my php code it comes out to be empty. But it is supposed to have the limit and offset value.
How to i send limit offset in $_GET?
You need to know how many records go on a page, and how many records there are.
Your SQL will end in OFFSET 30 LIMIT 10 (for example).
First get total Records. Page will come through your URL and default to page 1 if not set.
The offset is calculated like this (example, page 3):
$totalPages = ceil($totalRecords / $numPerPage); // round up the way.
$offset = ($page * $numPerPage) - $numPerPage; // (3 * 10 = 30) - 10 = offset 20
Your SQL will therefore grab records with OFFSET 20 LIMIT 10
This is what your server.php should looks like. Think you are missing some lines of code:
<?php
$table = 'employees';
$primaryKey = 'id'; // Table's primary key
$columns = array(
array( 'db' => 'id', 'dt' => 0 ),
array( 'db' => 'first_name', 'dt' => 1 ),
array( 'db' => 'last_name', 'dt' => 2 ),
array( 'db' => 'position', 'dt' => 3 ),
array( 'db' => 'date', 'dt' => 4 ),
array( 'db' => 'updated', 'dt' => 5 ),
);
$sql_details = array(
'user' => 'username',
'pass' => 'password',
'db' => 'database',
'host' => 'localhost'
);
require( 'ssp.class.php' );
echo json_encode(
SSP::simple( $_POST, $sql_details, $table, $primaryKey, $columns )
);
?>
End result: https://databasetable-net.000webhostapp.com/
This should get you in the right direction. Think the ssp.class.php file might need added too, unsure if you have it (you can find it on github). Hope this helps!
Related
I am building a news blog that upload posts every hour. I have created a shortcode that displays the last 15 posts on the home page. My problem was that the server cache needed to be deleted every hour. so I've decided to serve the post via AJAX so this area will get the latest posts every page load.
I found this answer and combine it whit my code.
My problem is that it displays all of the posts and not just 15.
PHP:
function get_ajax_posts() {
// Query Arguments
$args = array(
'post_type' => array('post'),
'post_status' => array('publish'),
'posts_per_page' => 15,
'nopaging' => true,
'order' => 'DESC',
'orderby' => 'date',
);
$ajaxposts = new WP_Query( $args );
$response = '';
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response .= get_template_part( 'template-parts/content-archive');
}
} else {
$response .= get_template_part('none');
}
echo $response;
exit; // leave ajax call
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
JS:
$.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "html",
data: { action : 'get_ajax_posts' },
success: function( response ) {
$( '.home-hot-flights' ).html( response );
//hot-flights
var hot_flights_item = $(".home-hot-flights article").width() + 17;
$(".art-move-left").click(function () {
$('.move-right').addClass('show-move-right');
var leftPos = $('.home-hot-flights').scrollLeft();
$(".home-hot-flights").animate({scrollLeft: leftPos - hot_flights_item}, 200);
});
$(".art-move-right").click(function () {
var leftPos = $('.home-hot-flights').scrollLeft();
$(".home-hot-flights").animate({scrollLeft: leftPos + hot_flights_item}, 200);
});
}
});
This might help you:
Pagination parameters
(nopaging (boolean) – show all posts or use pagination. Default value
is ‘false’, use paging. )
Display all posts by disabling pagination:
$query = new WP_Query( array( 'nopaging' => true ) );
I think you should remove that parameter if you want to display a certain number of posts using posts_per_page.
Try this piece of code I have edit your code please see below
function get_ajax_posts() {
// Query Arguments
$args = array(
'post_type' => array('post'),
'post_status' => array('publish'),
'posts_per_page' => 15,
'order' => 'DESC',
'orderby' => 'date',
);
wp_reset_query();
$ajaxposts = new WP_Query( $args );
$response = '';
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response .= get_template_part( 'template-parts/content-archive');
}
} else {
$response .= get_template_part('none');
}
echo $response;
exit; // leave ajax call
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
If the two loops data is overwridden then, I your first code wp_reset_query() is incorrect. If you are using WP_Query then
wp_reset_postdata() //remove wp_reset_query() which is used for wp_query()
should be used after the end of the WHILE loop which means that in your two loops you have to have
wp_reset_postdata() // use this at both loops
I am using ajax to send data to a custom rest endpoint. I am doing this because i'm creating a filter function on my WP site.
Now I am stuck trying to get the tax_query to work with my array of terms collected with JS on the front end. No matter what I do I cant seem to get this to work, and I am strongly suspecting this is only a minor error that I keep overlooking...
Just to clarify, the ajax sends the request successfully but the query returns all posts no matter what.
Here is the checkboxes used on the front end:
<div class="form-group">
<?php
if( $terms = get_terms( array( 'taxonomy' => 'utst', 'hide_empty' => false, 'orderby' => 'name' ) ) ) :
foreach ( $terms as $term ) :
echo '<div class="form-check">';
echo '<label class="form-check-label" for="'.$term->slug.'"><input class="form-check-input" type="checkbox" id="'.$term->slug.'" name="utstyrAr[]" value="'.$term->term_id.'"> '.$term->name.'</label>'; // ID of the category as the value of an option
echo '</div>';
endforeach;
endif;
?>
</div>
The JS (ajax function):
filterOppdrag(fiOppdrag) {
var utst = [];
var utstyrArray = document.getElementsByName("utstyrAr[]");
for (var i = 0; i < utstyrArray.length; i++) {
if(utstyrArray[i].type =='checkbox' && utstyrArray[i].checked == true) utst.push(utstyrArray[i].value);
}
console.log(utst);
$.ajax({
url: the.root + '/wp-json/myfilter/v1/filter',
type: 'GET',
data: {
'checkUtst' : utst,
},
success: (response) => {
console.log(response);
},
error: (response) => {
console.log(response);
}
});
}
And the wp_query (php):
function myFilter ($data) {
$checkUtst = sanitize_text_field($data['checkUtst']);
//Main $args
$args = array(
'post_type' => 'ml_opp', // Query only "ml_opp" custom posts
'post_status' => 'publish', // Query only posts with publish status
'orderby' => 'date', // Sort posts by date
'order' => 'ASC' // ASC or DESC
);
// for taxonomies / utstyr
if( isset( $utstyr ) )
$args['tax_query'] = array(
array(
'taxonomy' => 'ml_utst',
'field' => 'id',
'terms' => $checkUtst
)
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
This returns all the posts regardless of terms no matter what I pass through. I get no error messages and yes I have tested so that there is value in the array when I send it to the query. But what happens to it on the road there, I dont know. That's why i figure that Its probably just a rookie mistake I am making here.
Any help would be greatly appreciated!
Have you tried removing the wrapping array and not using a key?
$args = array(
'taxonomy' => 'ml_utst',
'field' => 'id',
'terms' => $checkUtst
);
I use server side processing files from the download as starting point with the ssp.class.php file. All works fine, but not the button. In the last column, I want to add some buttons. A lot to be found about this, but not working for me because I defined column data in php and not js. I can't put a function inside the column array like in the js examples.
I have the following code running:
<script type="text/javascript">
$(document).ready(function() {
pageSetUp();
var table = $('#dt_basic').dataTable({
"processing": true,
"serverSide": true,
"ajax": "index.php?loc=client/clients"
});
});
</script>
PHP
<?php
public function clients() {
$columns = array(
array( 'db' => 'id', 'dt' => 0 ),
array( 'db' => 'name', 'dt' => 1 ),
array( 'db' => 'address', 'dt' => 2 ),
array( 'db' => 'telephone', 'dt' => 3 ),
);
$table = 'clients';
$primaryKey = 'id';
$sql_details = array(
'user' => #####,
'pass' => #####,
'db' => #####,
'host' => #####
);
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
}
?>
Im trying to get server side processing working with concatenated columns.
I came across this this post: Datatables - Server-side processing - DB column merging
But when I use that format I get SQL errors. But I also want to insert say... a space between the fields... is this possible?
Edit:
Example:
Table init:
var customer_Table = $('#customer_Table').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "php/server_processing.php",
stateSave: true,
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
'order': 2, 'asc' ]],
"columns": [{"title":"id","visible":false,"type":"html-string"},{"title":"name","visible":true,"type":"html-string"},[{"title":"address","visible":true,"type":"html-string"}
} );
Column scheme:
$columns = array(
array( 'db' => 'id', 'dt' => "id" ),
array( 'db' => 'name', 'dt' => "Name" ),
array( 'db' => "`street` . ' ' . `city` . '<br>' . `postal` . ' ' . `country`" 'dt' => "address"
)
);
Error:
{"error":"An SQL error occurred: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`id`,`name`, `JCP`, ``street` . ' ' . `city` . '<br>' . `postal` . ' ' . `country``...' at line 1"}
Judging from the error message, the processing engine is expecting a valid column reference for 'db'. Each 'db' should refer to a valid column reference in the WHERE clause, and each 'dt' contains the label to be displayed for that column.
Your reference is, according to your snippet:
"`street` . ' ' . `city` . '<br>' . `postal` . ' ' . `country`"
Which doesn't mean much to most database engines I am familiar with. Try something like this:
$columns = array(
array( 'db' => 'id', 'dt' => "id" ),
array( 'db' => 'name', 'dt' => "Name" ),
array( 'db' => "CONCAT(`street`, ' ', `city`, '<br>', `postal`, ' ', `country`)",
'dt' => "address")
);
$columns = array(
array( 'db' => 'id', 'dt' => "id" ),
array( 'db' => 'name', 'dt' => "Name" ),
array( 'db' => "CONCAT(`street`, ' ', `city`, '<br>', `postal`, ' ', `country`)",
'as' => "address",
'dt' => "address")
);
I have a list of item and retrieving it in PHP array:
array(
'Daging Kambing Beku 2' => array(
(int) 4 => '80.00',
),
'Daging Rusa' => array(
(int) 32 => '4000.00'
),
'Sayur Kangkung' => array(
(int) 31 => '5000.00'
),
'Sayur Sawi' => array(
(int) 30 => '600.00',
(int) 29 => '4.00'
),
'Sayur Lemau' => array(
(int) 28 => '1.00'
),
'Sayur Sayuranj' => array(
(int) 27 => '1.00'
),
'Sayur Segar ke?' => array(
(int) 26 => '5.00'
),
'French Fries' => array(
(int) 25 => '90.00'
),
'Daging Arnab' => array(
(int) 33 => '5.00'
),
'Daging Kerbaul' => array(
(int) 34 => '20.00'
)
)
Array explain :
'Daging Kambing Beku 2' => array(
(int) 4 => '80.00',
),
'Daging Kambing Beku 2' is the name of item.
(int) 4 is the ID for the items table.
'80.00' is the price .
My problem is,I want to make a function add new Item each time Customer make an order.
I'd try using jquery read the PHP array and to add a list of item when Customer clicking "Add New Item" but it's failed.
I want to do something like this:
https://demo.phppointofsale.com/index.php/sales
Customer can add many Items without submitting page frequently.
I'm using CakePHP for my development.
I'll appreciate any kind of help. thanks.
Just a reminder, to use php array in js, you need to do some convertion like :
<script>
<?php echo "var js_array = ".json_encode($php_array).';'?>
</script>