jquery datatable with ajax based pagination - ajax

I have javascript function that populates datatable using Ajax. My javascript code looks like :
$('#results').dataTable({
// Ajax load data
"ajax": {
"url": "get_intl_tickets",
"type": "POST",
"data": {
"user_id": 451,
"csrfmiddlewaretoken" : csrftoken,
}
}
})
My server side script in django has a function that loads around 500 data rows. Now the problem is that I don't want to load whole data at a time. Instead I want to have first 10 data rows. Then with pagination, another 10 rows like that.
I read the page server side processing documentation of datatables. I tried with "serverSide": true option as well. I am not understanding server side script. There is given an example of PHP. It seems that they are not using any parameters like draw, recordsFiltered, recordsTotal there. There they have used php SSP class. And it is unknown what does it do. I am trying to implement it in django.
But I am not finding proper good documentation to implement. Any help will be appreciated.

Old question but one I also had a surprisingly difficult time finding an answer to, so in case anyone else ends up here... :P
I found this 2020 article very helpful, specifically part 6 showing the "complete code" that includes getting the correct variables, building the SQL query, and how to build/structure the data object that it responds with:
https://makitweb.com/datatables-ajax-pagination-with-search-and-sort-php/
Their example posted below:
<?php
## Database configuration
include 'config.php';
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($con,$_POST['search']['value']); // Search value
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " and (emp_name like '%".$searchValue."%' or
email like '%".$searchValue."%' or
city like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of record with filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city']
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);

Nice exemple:
https://datatables.net/examples/server_side/defer_loading.html
But you need edit server side.
Response demo
{
draw:2,
recordsFiltered:57,
recordsTotal:57
}

Related

Save multiple inputs Laravel 5.6

I'm trying to save a data to my database coming from 2 inputs which has multiple values. The scenario is that after a product has been saved, data will be save to my another table with columns 'product_id','price','size'. How ever when I tried to run my code, only the first value is saved in the column 'size', the data in 'price' are fine.
<input name="fix_size[]">
<input name="fix_price[]">
foreach($request->fix_price as $prc){
$cprice = new ContainerPrice;
$cprice->product_id = $id;
$cprice->price = $prc;
foreach($request->fix_size as $size){
$cprice->size = $size;
}
$cprice->save();
}
Remember, fix_size and fix_price are arrays.
You have to get the respective pairs of each fix_size and fix_price. So you have to monitor the index in the loop.
This is one of the possible solution in your problem:
$fix_sizes = $request->fix_size;
foreach($request->fix_price as $i => $prc){
$cprice = new ContainerPrice;
$cprice->product_id = $id;
$cprice->price = $prc;
$cprice->size = $fix_sizes[$i];
$cprice->save();
}
I may suggest to you to master the basic principles of programming and learn to debug codes by yourself.
Try this
foreach($request->fix_price as $prc){
foreach($request->fixed_size as $size){
$cprice = new ContainerPrice;
$cprice->product_id = $id;
$cprice->price = $prc;
$cprice->size = $size;
$cprice->save();
}
}
You could try this:
foreach($request->fix_price as $key => $prc) {
$cprice = new ContainerPrice;
$cprice->product_id = $id;
$cprice->price = $prc;
$cprice->size = $request->input('size')[$key];
$cprice->save();
}
The problem you had is because you loop over all elements inside the main loop and keeping only the last element. In other words, in the foreach loop, you are constantly overriding the $cprice->size property with the last you find.
Now with this code you access the "size" which has the same index as your "price".

$_SESSION variables use in queries

I have spent nearly two days going in circles on this one.
I seem to have difficulty using $_SESSION or $_POST as strings in any query or converting them to strings to use.
I am using a simple hash approach to login to a site.
Extract from script is
<?php
session_start();
echo "******Running Authenticate<br>";
echo "data submitted<br>".$_POST['site_login']."<br>".$_POST['site_password']."<br><br>";
$SiteLogin = $_POST['site_login']
$_SESSION['site_login'] = $_POST['site_login'];
$_SESSION['site_password'] = $_POST['site_password'];
$_SESSION['session_id'] = session_id();
$_SESSION['Now_val'] = date('Y-m-d H:i:s');
//include 'showallvars.php';
include 'dbconfig.php';
// Prepare our SQL
if ($stmt = $con->prepare('SELECT site_index, site_password FROM web_sites WHERE site_login = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['site_login']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
echo "account exists";
}
else
{
header('Location: badindex.php');
}
if (password_verify($_POST['site_password'], $password)) {
// Verification success! User has loggedin!
echo "password good";
}
else
{
header('Location: badindex.php');
}
}
$_SESSION['loggedin'] = TRUE;
?>
that works fine
BUT there is another field ( 'site_name') in the record which i want to carry forward.
This should be easy !!
and there is a dozen ways of doing it
for example the "standard" example is something like
$name = $mysqli->query("SELECT site_name FROM web_sites WHERE site_login = 'fred'")->fetch_object()->site_name;
That works fine
but no matter how i try - concatenating or or ... I cannot get $_SESSION['site_login'] or $_POST['site_login'] to replace 'fred'.
There seems to be white space added in.
Assistance or guidance ?
It should be possible to as easy as doing the following:
So:
if ($stmt = $con->prepare('SELECT site_index, site_password
FROM web_sites WHERE site_login = ?')) {
becomes:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $SiteLogin)) {
Do note, it is bad practice to do directly parse $SiteLogin to a query, because now someone can SQL Inject this and hack your website. All they need to do is use your form and figure out that which field is responsible for $SiteLogin. You would need to escape your $SiteLogin. Assuming Mysqli, it would become:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $con->real_escape_string($SiteLogin))) {
Thank you for that BUT the instant I saw the curly brackets in your answer - it all came flooding back to me. I had forgotten that PHP has problems with the square brackets
$sql = ("SELECT site_name FROM web_sites WHERE site_login = '". $_SESSION{'site_login'} ."' LIMIT 1");
I KNEW it was easy !
Your comments on injection are of course correct but this was an edited code excerpt and $SiteLogin was just added in as a "temporary working variable if needed"

Yii2 call 2 functions on change of a dropdown

I have several dropdown imputs and on change of any of them I wanna a value to be offered for a textbox.
I have a code that i placed on each of my dropdown's and it works perfect for me:
<?= $form->field($model4, 'prevoditelj')->dropDownList(ArrayHelper::map(
\app\models\Prevoditelj::find()->orderBy('idprevoditelj')->asArray()->all(),
'idprevoditelj',
'naziv'
),['onchange'=>'
$.get( "'.Url::base().'/index.php?r=zadatak/trosak&id='.$model->projekt.'_"+$("#'.Html::getInputId($model3, 'usluga').'").val()+"_"+$("#'.Html::getInputId($model3, 'dodatak').'").val()+"_"+$("#'.Html::getInputId($model3, 'obr_jedinica').'").val()+"_"+$("#'.Html::getInputId($model4, 'prevoditelj').'").val(), function( data ) {
$( "#'.Html::getInputId($model, 'trosak').'" ).val( data );
});
']) ?>
in a controller I have:
public function actionCijena($id){
$sve=explode("_",$id);//0 - projekt_id, 1 - usluga, 2 - dodatak/jez_kombinacija, 3 - obr_jedinica
$projekt = Projekt::findone($sve[0]);
$klijent = Klijent::findone($projekt['klijent']);
$cjenik_klijent = CjenikKlijent::find()
->asArray()
->where('klijent = :id and usluga = :usluga_id and obr_jedinica = :obr_jedinica and jez_kombinacija = :jez_kombinacija and valuta = :valuta',
['id'=>$klijent['idklijent'],'usluga_id'=>$sve[1],'obr_jedinica'=>$sve[3],'jez_kombinacija'=>$sve[2],'valuta'=>$klijent['valuta']])
->all();
//ako nema, gledaj opci cjenik
if($cjenik_klijent==array()){
$cjenik_klijent = CjenikOpci::find()
->asArray()
->where('usluga = :usluga_id and obr_jedinica = :obr_jedinica and jez_kombinacija = :jez_kombinacija and valuta = :valuta',
['usluga_id'=>$sve[1],'obr_jedinica'=>$sve[3],'jez_kombinacija'=>$sve[2],'valuta'=>$klijent['valuta']])
->all();
}
return $cjenik_klijent[0]['cijena'];
}
The problem I have is that now I wanna add another calculated value to another textbox. but it needs to trigger on the same dropdown's. Unfortunately Get can't return an array so I need to split it up into 2 functions, but how do I call 2 of them?
Ok, I managed to find a solution in returning 2 values in 1 string and then exploding them in jquery. Don't know why I didn't think of that sooner.

Change the maximum amount of characters in the Meta Description

I have a problem to change the limit of characters in the meta description. I\\’ve modified as shown here:
http://www.magentocommerce.com/boards/v/viewthread/278911/#t392935
But it only detects if you create or modify the product from magento admin and I upload products from .csv file and I have to go one by one to each product in the meta description and then go down from 255 to 155: (
Is there any way to change it without changing it from Magento, I think the problem comes because the code says:
setOnkeyup
Thanks in advance and greetings!
I understand, that you have too long data in your meta_description for each of products.
You can short the value before loading it by layout XML config, or directly by the PHTML template for each page type.
Better way to have result you need is NOT ti import longest data than you need.
Importing unnecessary data solving import and after that you need to correct it again.
Maybe will be better to make script to cut-out meta description in CSV file before you start import to magento.
I solved simmilar issue and make something like this:
(script take your csv file and make new with only 2 columns, SKU and updated text named DECSRIPTION, than you can import to magento after your firs import of csv (first import everything without meta description, after that ONLY your meta description cuted out by 250 chars for example))
//////// get csv and take variable you need in my case is it SKU
$csv = file_get_contents ('myimportfile.csv');
function parse_csv ($csv_string, $delimiter = ";", $skip_empty_lines = true, $trim_fields = true)
{
$enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
$enc = preg_replace_callback(
'/"(.*?)"/s',
function ($field) {
return urlencode(utf8_encode($field[1]));
},
$enc
);
$lines = preg_split($skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s', $enc);
return array_map(
function ($line) use ($delimiter, $trim_fields) {
$fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
return array_map(
function ($field) {
return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
},
$fields
);
},
$lines
);
}
// list of variables to array
$vystup = parse_csv($csv);
enter code here
After that you can loop each variable to row, modify by PHP what you want:
$seznamsku = array();
foreach ($vystup as $row){
array_push($seznamsku, $sku[0]);
unset($seznamsku[0]);
$seznamskufin = array_filter($seznamsku, 'strlen');
};
foreach ($seznamskufin as $row) {
$__OUT .= ' "ROW_YOURSKU","'.htmlspecialchars(substr(ROW_YOURMETADESCRIPTION, 0, 155)).'"'."\n"; // TODO exactly dont know how to call variables, maybye $row['something'] or $row[0]['something']
};
$feed = fopen($newfile, 'w');
fwrite($feed, $__OUT);
fclose($feed);
//remember to unset variables
you can get another csv file with description long 250 chars and import it to magento
(You must update code it only returns list of SKU, get your descriptions from file);

How to set Component parameters in J2.5?

I've created a J2.5 component with some config fields using config.xml in the admin folder of the component.
How can I set parameters in the config programatically?
I've tried the code bellow, but it obviously doesn't save the result to the DB:
$params = & JComponentHelper::getParams('com_mycomponent');
$params->set('myvar', $the_value);
Could anyone please show some examples of how to achieve this?
The safest way to do this would be to include com_config/models/component.php and use it to validate and save the params. However, if you can somehow validate the data params yourself I would stick with the following (much more simple solution):
// Get the params and set the new values
$params = JComponentHelper::getParams('com_mycomponent');
$params->set('myvar', $the_value);
// Get a new database query instance
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Build the query
$query->update('#__extensions AS a');
$query->set('a.params = ' . $db->quote((string)$params));
$query->where('a.element = "com_mycomponent"');
// Execute the query
$db->setQuery($query);
$db->query();
Notice how I cast the params to a string (when building the query), it will convert the JRegistry object to a JSON formatted string.
If you get any caching problems, you might want to run the following after editing the params:
From a model:
$this->cleanCache('_system');
Or, else where:
$conf = JFactory::getConfig();
$options = array(
'defaultgroup' => '_system',
'cachebase' => $conf->get('cache_path', JPATH_SITE . '/cache')
);
$cache = JCache::getInstance('callback', $options);
$cache->clean();
The solution is here...
http://www.webtechriser.com/tutorials/82-joomla-3-0/86-how-to-save-component-parameters-to-database-programmatically
You can replace in Joomla 2.5+ the
// check for error
if (!$table->check()) {
$this->setError('lastcreatedate: check: ' . $table->getError());
return false;
}
if (!$table->store()) {
$this->setError('lastcreatedate: store: ' . $table->getError());
return false;
}
with
if (!$table->save()) {
$this->setError('Save Error: ' . $table->getError());
return false;
}

Resources