Script for search column:
<script>
$.fn.dataTable.ext.errMode = 'none';
var tableObj;
$(document).ready(function(){
// debugger;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
tableObj = $('{{ $class_name }}').DataTable({
searchable: true,
processing: true,
serverSide: true,
"aaSorting": [],
cache: true,
type: 'GET',
ajax: '{{ $routeValue }}',
#if(isset($table_columns))
columns: {!!$setData!!}
#endif
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var input = document.createElement("input");
$(input).appendTo($(column.header()))
.on('keyup', function () {
column.search($(this).val(), false, false, true).draw();
});
});
}
});
$('.datatable').find('select.form-control').removeClass('form-control input-sm').addClass('full-width').attr('data-init-plugin','select2');
});
// console.log("it is working");
</script>
Controller function to get data:
$records = array();
dd($record);
$records = User::join('roles', 'users.role_id', '=', 'roles.id')
->select(['users.id','users.name', 'phone','users.default_bill_address','area','users.created_at','website','user_status','reason_inactive','is_online','login_enabled','role_id',
'slug'])->orderBy('users.created_at', 'desc');
if(!isset($_GET['order'])){
$records = $records ->whereIn('users.id',$list_his)->orderBy('users.created_at', 'desc');
}
return Datatables::of($records)
->editColumn ('default_bill_address', function($records){
if($records->default_bill_address)
{
$add = Address::where('id',$records->default_bill_address)->first();
if($add)
return $add->fullAddress();
else
return '-';
}
else
return '-';
})
Screenshot:
screenshot related to panel where search column is present.
Description
I have edited many columns in the same way from different tables, when I search in the specific column it returns nothing, because related text is not in the query table and I cannot join so many tables to get the result while searching.
Simplest solution i got
In your script just cahnge a single line serverSide: true to serverSide: false,
<script>
$.fn.dataTable.ext.errMode = 'none';
var tableObj;
$(document).ready(function(){
// debugger;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
tableObj = $('{{ $class_name }}').DataTable({
searchable: true,
processing: true,
serverSide: false,
"aaSorting": [],
cache: true,
type: 'GET',
ajax: '{{ $routeValue }}',
#if(isset($table_columns))
columns: {!!$setData!!}
#endif
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var input = document.createElement("input");
$(input).appendTo($(column.header()))
.on('keyup', function () {
column.search($(this).val(), false, false, true).draw();
});
});
}
});
$('.datatable').find('select.form-control').removeClass('form-control input-sm').addClass('full-width').attr('data-init-plugin','select2');
});
// console.log("it is working");
</script>
this will change the server side searching into client-side.
search from the content not from the datatable.
How silly i was mistaking
Related
I'm trying to send via AJAX data, I'm doing a post and then receiving it on the laravel controller.
I'm getting an error that the data is null.
I tried multiples ways to fix it but I'm not able to figure out how to do it.
Ajax:
$(document).ready(function () {
$('table tbody').sortable({
update: function (event, ui) {
$(this).children().each(function (index) {
if ($(this).attr('data-position') != (index + 1)) {
$(this).attr('data-position', (index + 1)).addClass('updated');
}
});
saveNewPositions();
}
});
});
function saveNewPositions() {
var positions = [];
$('.updated').each(function () {
positions.push([$(this).attr('data-index'), $(this).attr('data-position')]);
$(this).removeClass('updated');
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(positions);
$.ajax({
url: 'cursos',
method: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(positions),
contentType: "application/json; charset=utf-8",
traditional: true,
})
}
Laravel Controller:
public static function updateOrder(Request $request)
{
foreach ($request->positions as $position) {
$index = $position[0];
$newPosition = $position[1];
$seccion = SectionCourse::findOrFail($index);
$seccion->order = $newPosition;
$seccion->save();
}
return response('success', 200);
}
Doing a dd of the request, I receive this:
I fixed it using $request->toArray() instead of $request->positions directly
I'am using dropzone js to upload multiple images (dropzone programmatically).
Upload files, it's ok.
But when I remove a file, some error occurred:
500 Internal Server Error (Method App\Modules\Product\Controllers\ProductController::delete does not exist - I don't have delete() method in controller - why?).
Cannot read property 'removeChild' of null
My route
Route::post('/adminks/products/delete/dropzone', 'ProductController#deleteImageDropzone')->name('be.delete.dropzone');
My Controller
public function deleteImageDropzone(Request $request) {
$image = $request->filename;
ProductImage::where(['image_name' => $image, 'model' => 'Product', 'module' => 'Product'])->delete();
$path = public_path().'/uploads/images/product/product/'.$image;
if (file_exists($path)) {
unlink($path);
}
return $image;
}
My JS
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#dropzone_images", {
url: "{{ route('be.upload.dropzone') }}",
sending: function (file, xhr, formData) {
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
var code = '{{ $code }}';
formData.append('code', code);
},
paramName: 'others_image',
addRemoveLinks: true,
acceptedFiles: '.jpeg,.jpg,.png,.gif',
dictRemoveFile: 'Xóa ảnh',
init: function() {
this.on("removedfile", function(file) {
var name = file.upload.filename;
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
},
type: 'POST',
url: '{{ url('/adminks/products/delete/dropzone') }}',
data: { filename: name },
success: function (data){
console.log("File has been successfully removed!!");
},
error: function(e) {
console.log(e);
}});
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
});
}
});
Any solution? All comments are respected!
Thanks so much!
I'm trying to make this code to work but it look I'm doing something wrong when passing the two variables with ajax, please help, here is the code, basically is a drag and drop code to move items between boxes and organize inside each box.
<script type="text/javascript">
$(document).ready(function() {
// Example 1.3: Sortable and connectable lists with visual helper
$('#sortable-div .sortable-list').sortable({
connectWith: '#sortable-div .sortable-list',
placeholder: 'placeholder',
delay: 150,
stop: function() {
var selectedData = new Array();
$('.sortable-list>li').each(function() {
selectedData.push([$(this).attr("id"), $(this).attr("pagenum")])
});
updateOrder(selectedData);
}
});
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data,
page: data
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
</script>
You can make it using this way:
$('.spremiUredivanje').click(function(){
ai = document.getElementById('ai_mjerila_edit').value;
broj_mjerila = document.getElementById('broj_mjerila_edit').value;
adresa = document.getElementById('adresa_edit').value;
stanje = document.getElementById('stanje_edit').value;
$( "#datum_edit" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
datum = document.getElementById('datum_edit').value;
operater = document.getElementById('operater_edit').value;
$.ajax({
url: 'test.php',
type: 'POST',
data: {
post1: broj_mjerila, post2: adresa, post3:stanje, post4: datum, post5: operater, post6:ai
},
beforeSend: function(){
$('#loaderEdit').show();
},
So your php file should look like this:
$broj_mjerila = $_POST['post1'];
$adresa = $_POST['post2'];
$stanje = $_POST['post3'];
$datum = $_POST['post4'];
$operater = $_POST['post5'];
$ai = $_POST['post6'];
To control your response use success inside ajax call:
success: function(response) {
if(response == 1) {
//alert("success!");
$('#editUspjesan').show();
$('#loaderEdit').hide();...
Can you explain your requirement clear. Are you trying to get page number and id in 2 separate array?
// If page no and id need to be in separate array
var position = [], pages = [];
$('.sortable-list>li').each(function() {
position.push($(this).attr("id"));
pages.push($(this).attr("pagenum"));
});
updateOrder(position, pages);
function updateOrder(position, page) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: position,
page: page
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
// If page no and id can be combined use objects
var selectedData = [];
$('.sortable-list>li').each(function() {
selectedData.push({id: $(this).attr("id"), page: $(this).attr("pagenum")})
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
<script type="text/javascript">
$(document).ready(function() {
// Example 1.3: Sortable and connectable lists with visual helper
$('#sortable-div .sortable-list').sortable({
connectWith: '#sortable-div .sortable-list',
placeholder: 'placeholder',
delay: 150,
stop: function() {
var selectedData = new Array();
$('.sortable-list>li').each(function() {
selectedData.push([$(this).attr("id"), $(this).attr("pagenum")])
});
updateOrder(selectedData);
}
});
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data.id,
page: data.pagenum
},
dataType:'json',
success: function() {
/* alert('your change successfully saved');*/
}
})
}
</script>
Let's try this one
I have implemented data-tables fixed columns on project, the first (patients_report) data-tables report works very well but the second(visitation_report) one fails please advise how can I solve this problem ?
Below is my code :
<script type="text/javascript" src="http://www.datatables.net/release-datatables/media/js/jquery.js"></script>
<script type="text/javascript" src="http://www.datatables.net/release-datatables/media/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="http://www.datatables.net/release-datatables/extensions/FixedColumns/js/dataTables.fixedColumns.js"></script>
<link href='http://www.datatables.net/release-datatables/media/css/jquery.dataTables.css' rel='stylesheet'>
<link href='http://www.datatables.net/release-datatables/extensions/FixedColumns/css/dataTables.fixedColumns.css' rel='stylesheet'>
<script type="text/javascript">
var j = jQuery.noConflict();
j(document).ready(function () {
j(document).ready(function () {
var table = j('.patients_report').DataTable({
scrollY: "300px",
scrollX: true,
scrollCollapse: true,
paging: false
});
new j.fn.dataTable.FixedColumns(table, {
leftColumns: 0,
rightColumns: 1
});
fc.fnUpdate();
});
j(document).ready(function () {
var visitation_table = j('.visitation_report').DataTable({
scrollY: "300px",
scrollX: true,
scrollCollapse: true,
paging: false
});
new j.fn.dataTable.FixedColumns(visitation_table, {
leftColumns: 0,
rightColumns: 1
});
fc.fnUpdate();
});
j('.edit_patient_link').click(function () {
//get data
var patient_id = j(this).closest('tr').find('input[name="view_patient_id"]').val();
j.ajax({
type: "GET",
url: "<?php echo base_url(); ?>reports/get_patient_reports_details/" + patient_id,
dataType: "json",
success: function (response) {
j('#edit_patient_id').val(response[0].patient_id);
j('#edit_title').val(response[0].title);
j('#edit_phone_no').val(response[0].phone_no);
j('#edit_inputFirstName').val(response[0].f_name);
j('#edit_inputSurName').val(response[0].s_name);
j('#edit_inputOtherName').val(response[0].other_name);
j('#edit_dob').val(response[0].dob);
j('#edit_gender').val(response[0].gender);
j('#edit_maritalstatus').val(response[0].marital_status);
j('#edit_nationalid').val(response[0].identification_number);
j('#edit_email').val(response[0].email);
j('#edit_address').val(response[0].address);
j('#edit_residence').val(response[0].residence);
j('#edit_employement_status').val(response[0].employment_status);
j('#edit_employers_name').val(response[0].employer);
j('#edit_kinname').val(response[0].next_of_kin_fname);
j('#edit_kinsname').val(response[0].next_of_kin_lname);
j('#edit_kinrelation').val(response[0].next_of_kin_relation);
j('#edit_kinphone').val(response[0].next_of_kin_phone);
j('#edit_family_number').val(response[0].family_base_number);
},
error: function (data) {
}
});
});
j('.view_patient_link').click(function () {
//get data
var patient_id = j(this).closest('tr').find('input[name="view_patient_id"]').val();
j.ajax({
type: "GET",
url: "<?php echo base_url(); ?>reports/get_patient_reports_details/" + patient_id,
dataType: "json",
success: function (response) {
j('#view_patient_id').val(response[0].patient_id);
j('#view_title').val(response[0].title);
j('#view_phone_no').val(response[0].phone_no);
j('#view_inputFirstName').val(response[0].f_name);
j('#view_inputSurName').val(response[0].s_name);
j('#view_inputOtherName').val(response[0].other_name);
j('#view_dob').val(response[0].dob);
j('#view_gender').val(response[0].gender);
j('#view_maritalstatus').val(response[0].marital_status);
j('#view_nationalid').val(response[0].identification_number);
j('#view_email').val(response[0].email);
j('#view_residence').val(response[0].residence);
j('#view_employement_status').val(response[0].employment_status);
j('#view_employers_name').val(response[0].employer);
j('#view_kinname').val(response[0].next_of_kin_fname);
j('#view_kinsname').val(response[0].next_of_kin_lname);
j('#view_kinrelation').val(response[0].next_of_kin_relation);
j('#view_kinphone').val(response[0].next_of_kin_phone);
j('#view_family_number').val(response[0].family_base_number);
},
error: function (data) {
}
});
});
j('.delete_patient_link').click(function () {
//get data
var patient_id = j(this).closest('tr').find('input[name="view_patient_id"]').val();
j('.input_patient_id_delete').val(patient_id);
});
});
</script>
<style>
/* Ensure that the demo table scrolls */
th, td { white-space: nowrap; }
div.dataTables_wrapper {
width: 1000px;
margin: 0 auto;
}
</style>
I can't see clearly what is the problem with your code. But I assume that is in first part, so put everything in single document ready event. Like this :
j(document).ready(function () {
var table = j('.patients_report').DataTable({
scrollY: "300px",
scrollX: true,
scrollCollapse: true,
paging: false
});
new j.fn.dataTable.FixedColumns(table, {
leftColumns: 0,
rightColumns: 1
});
table.fnUpdate();
var visitation_table = j('.visitation_report').DataTable({
scrollY: "300px",
scrollX: true,
scrollCollapse: true,
paging: false
});
new j.fn.dataTable.FixedColumns(visitation_table, {
leftColumns: 0,
rightColumns: 1
});
visitation_table.fnUpdate();
// rest of code
...
}); // close document ready event callback
There is fc.fnUpdate(); but I can't find fc variable nowhere. That should have been dataTable object. I hope this will do the trick. Good luck with project.
I have tried these JS code combos:
var aion_settings = [];
function aion_save_settings(){
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:{
settings: function(){
return aion_settings;
},
other_data: 'Other Data'
},
success:function(result){
console.log(result);
}
});
}
and...
function aion_save_settings(){
var aion_settings = [];
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:{
settings: aion_settings,
other_data: 'Other Data'
},
success:function(result){
console.log(result);
}
});
}
..and
var aion_settings = [];
function aion_save_settings(){
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:{
settings: aion_settings,
other_data: 'Other Data'
},
success:function(result){
console.log(result);
}
});
}
..and these combos with:
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:aion_settings,
success:function(result){
console.log(result);
}
});
On this JQuery page it even has this example:
var xmlDocument = [create xml document];
var xmlRequest = $.ajax({
url: "page.php",
processData: false,
data: xmlDocument
});
xmlRequest.done(handleResponse);
On the receiving side, I have this PHP code:
$app->post('/save_settings',function() use ($app){
$aion_settings=$app->request()->post();
var_dump($aion_settings);
//Save the aion_settings
if(aion_logged_in_user_super()){
global $aion_db;
if(is_array($aion_settings)) foreach($aion_settings as $setting_key => $setting){
//Get the setting's ID
$current_setting = array();
$current_setting = $aion_db->queryFirstRow("SELECT id FROM settings WHERE setting_key=%s",$setting_key);
if(!isset($current_setting['id'])) $current_setting['id']=NULL;
$aion_db->insertUpdate('settings',array(
'id'=>$current_setting['id'],
'setting_key'=>$setting_key,
'value'=>serialize($setting)
));
}
}
});
The aion_settings is setup correctly just before the $.ajax request is sent. But, the object settings is not caught on the PHP side, though other_data is caught? The last line below shows the object ready via console.log but not set via $.ajax. I'm stumped, any help?
The data parameter of your $.ajax function should have the following format:
data: {
'settings': aion_settings,
'other_data': 'Other Data'
},
This is how I fixed it:
JS Side:
function aion_save_settings(){
var aion_settings = new Object();
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:aion_settings,
success:function(result){
console.log(result);
}
});
}
PHP Side:
$app->post('/save_settings',function() use ($app){
$aion_settings=$app->request()->post();
var_dump($aion_settings);
//Save the aion_settings
if(aion_logged_in_user_super()){
global $aion_db;
if(is_array($aion_settings)) foreach($aion_settings as $setting_key => $setting){
//Get the setting's ID
$current_setting = array();
$current_setting = $aion_db->queryFirstRow("SELECT id FROM settings WHERE setting_key=%s",$setting_key);
if(!isset($current_setting['id'])) $current_setting['id']=NULL;
$aion_db->insertUpdate('settings',array(
'id'=>$current_setting['id'],
'setting_key'=>$setting_key,
'value'=>serialize($setting)
));
}
}
});
Please compare with my question above.