jQuery AJAX loading page content - javascript

I'm trying to rebuild my site, so that it uses AJAX to load data content inside a div.
This is the function, that handles the loading:
navigate = function(url, title, callback){
//show message to user
toastr.info('<i class="fa fa-spin fa-circle-o-notch"></i> Page is being loaded, please wait.');
//default variables set
title = title || url.substr(url.lastIndexOf('/') + 1).replace(/_/g, ' ').capitalize();
callback = callback || function(){};
//load content to wrapper
$("#content-wrapper").load(url + "?" + $.param({page_load: true}), function(res, status, jqXHR){
toastr.clear(); //hides message
if(status === "error")
{
toastr.error('Page couldn\'t be loaded. Please try again later or contact your system administrator', jqXHR.status + ": " + jqXHR.statusText);
}
else if(status === "success")
{
History.pushState({page: url}, title + " | PCexpres manager", url);
}
//remove modals from inside the content and move them to the end of body - prevents problems with backdrop
$('body > .modal').remove();
$('.modal').each(function(){
$(this).clone(true, true).appendTo("body");
$(this).remove();
})
//execute custom callback
callback(res, status, jqXHR);
})
}
The problem is, that the content, which is being loaded, often (usually) contains more JS (libraries as well as script tags with my code), which is usually not executed correctly. Example of such response:
<script type="text/javascript" src="http://pce.local/assets/js/plugins/datatables/datatables.js?1434971835"></script>
<script type="text/javascript" src="http://pce.local/assets/js/plugins/datatables/extensions/ColReorder/js/dataTables.colReorder.min.js?1434972105"></script>
<link type="text/css" rel="stylesheet" href="http://pce.local/assets/css/plugins/datatables/datatables.css?1434971143" />
<script>
$(function() {
$('.table').dataTable({
dom: 'Rlfrtip',
stateSave: true,
processing: true,
serverSide: true,
searchHighlight: true,
ajax: "http://pce.local/technician/customers/index_processing.json",
columns: [{
data: "checkbox",
name: "return 'id'"
}, {
data: "id",
name: "return 'id'"
}, {
data: "last_name",
name: "return 'last_name'"
}, {
data: "first_name",
name: "return 'first_name'"
}, {
data: null,
render: function(customer) {
return customer.address + (((customer.address_city !== "" || customer.address_zip !== "") && (customer.address !== "")) ? ", " : "") + customer.address_zip + " " + customer.address_city;
},
name: "return 'first_name'"
}, {
data: "email",
name: "return 'email'"
}, {
data: "phone1",
name: "return 'phone1'"
}, {
data: "actions",
name: "return 'id'"
}],
stateSave: true,
order: [
[1, "desc"]
],
aoColumnDefs: [{
'bSortable': false,
'aTargets': [0, -1]
}],
iDisplayLength: 50,
language: {
lengthMenu: "Display <select><option value='25'>25</option><option value='50'>50</option><option value='100'>100</option><option value='200'>200</option><option value='500'>500</option></select> records per page"
}
});
$(".check_all").change(function() {
$(".content_wrapper :checkbox").prop("checked", $(this).is(":checked"))
})
$("#delete_checked").click(function() {
var ids = '';
$(".delete_one:checked").each(function() {
ids += $(this).attr('data-id') + ',';
})
//remove last comma
ids.slice(0, -1)
if (confirm('Are you sure?'))
window.location.href = "http://pce.local/technician/customers/delete/" + ids
})
$(document).on('click', '.delete_customer', function(e) {
e.preventDefault();
$me = $(this);
bootbox.dialog({
title: "Delete customer?",
message: "Are you sure, you want to delete this customer?",
buttons: {
nope: {
label: "No",
className: "btn-default",
callback: function() {
toastr.success('Deletion cancelled');
}
},
yep: {
label: "Yes",
className: "btn-warning",
callback: function() {
window.location.href = $me.attr('href');
}
},
yeah: {
label: "Yes, delete data as well",
className: "btn-danger",
callback: function() {
window.location.href = $me.attr('href') + '/1';
}
}
}
});
})
});
</script>
<div class="content_wrapper">
<a class="btn btn-primary btn-md" href="http://pce.local/technician/customers/add">+</a>
<table class="table table-condensed table-striped table-hover pce-list_table">
<thead>
<th>
<input class="check_all" name="check_all" value="1" type="checkbox" id="form_check_all" />
</th>
<th>ID</th>
<th>Last name</th>
<th>First name</th>
<th>Address</th>
<th>E-mail</th>
<th>Phone</th>
<th>Actions</th>
</thead>
<tfoot>
<th>
<input class="check_all" name="check_all" value="1" type="checkbox" id="form_check_all" />
</th>
<th>ID</th>
<th>Last name</th>
<th>First name</th>
<th>Address</th>
<th>E-mail</th>
<th>Phone</th>
<th>Actions</th>
</tfoot>
<tbody>
</tbody>
</table>
<button id="delete_checked" class="btn btn-primary btn-md" data-nosubmit="data-nosubmit" name="delete_checked">Delete checked</button>
</div>
Is there any proper way to load such content and execute the js as if it was a normal page load?

Here is the correct way to execute javascript after ajax response is added to the container
var arr = document.getElementById('myDiv').getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
{
eval(arr[n].innerHTML)//run script inside div
}

Related

How to create JS class and use of class object in Laravel 8?

Controller load the view and load the jQuery.
index.blade.php
<table id="UserGrid" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Country</th>
<th>Dept</th>
<th>Title</th>
<th>Username</th>
<th>Role</th>
<th>Status</th>
<th>Created at</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
#php
$pageJsScript = array(
'<script type = "text/javascript" src="js/setting/user/User_search.js")></script>'
);
$pageJsCalls = array(
'User_search.init();'
);
#endphp
The above code is in between the <section> tags
In my master page I call these functions:
<?php foreach ($pageJsScript as $jsScript)
{
echo $jsScript.PHP_EOL;
}
?>
<script>
jQuery(document).ready(function() {
Apps.init();
<?php foreach ($pageJsCalls as $jsCall)
{
echo $jsCall.PHP_EOL;
}
?>
});
</script>
And the then I created a separated file kept in JS folder:
var User_search = function () {
var DataGrid = $('#UserGrid');
var loadGridUrl = "{{url('/show_user_list')}}";
var dataTable = null;
var loadGrid = function () {
alert('called');
var url = loadGridUrl;
dataTable = DataGrid.DataTable({
dom: "Blfrtip",
aaSorting: [], //disabled initial sorting
ajax: url,
paging: true,
searching: true,
info: true,
processing: true,
serverSide: false,
lengthMenu: [[25, 50, 100, 200, 500], [25, 50, 100, 200, 500]],
pageLength: 25,
"columnDefs": [
{"width": "13%", "targets": 4, "class":'word-wrap'},
],
buttons: [
{extend: "csv"}
],
columns: [
//Table Column Header Collection
{data: "id"},
{data: "name"},
{data: "field_office"},
{data: "department"},
{data: "designation"},
{data: "email"},
{data: "role"},
//{data: "is_locked"},
{
data: null, render: function (data, type, row) {
if (data.is_locked == '1') {
return '<span class="label label-warning label-sm">Pending</span>';
}
else if (data.is_locked == '2') {
return '<span class="label label-success label-sm">Unlock</span>';
}
else if (data.is_locked == '3') {
return '<span class="label label-danger label-sm">Locked</span>';
}
}
},
{data: "created_at"},
{
data: null, render: function (data, type, row) {
// Combine the first and last names into a single table field
if(user_id==1 || user_id==21) {
return '<i class="fa fa-edit"></i> Edit' +
'| <i class="fa fa-trash-o"></i> Delete';
}else {
return '';
}
}
},
],
});
$("#UserGrid_tools > li > a.tool-action").on("click", function () {
var e = $(this).attr("data-action");
dataTable.button(e).trigger();
});
$(".dt-buttons").hide();
jQuery('#UserGrid_wrapper .dataTables_filter input').addClass("form-control input-small"); // modify table search input
jQuery('#UserGrid_wrapper .dataTables_length select').addClass("form-control input-small"); // modify table per page dropdown
jQuery('#UserGrid_wrapper .dataTables_length select').select2(); // initialize select2 dropdown
}
return {
//main function to initiate the module,
init: function () {
//Grid loading
if (!jQuery().dataTable) {
return;
}
loadGrid();
},
};
}();
Kindly guide me in order to get run all things, infact alert is working by the function loadGrid() is not working.

Getting 500 while adding data to datatables in javascript .net mvc

So i'm trying to add data to datatable, i'm relatively new to Web Applications, i'm more of a mobile app developer
I've looked into a few examples and i've come up with a solution to do it, but for some reason i'm getting this error on chrome
DataTables warning: table id=personaliseDatatable - Ajax error. For more information about this error, please see http://datatables.net/tn/7
And if i check the console i'm getting Internal Server Error 500, but in fact the controller is getting triggered and i'm able to get the data from the repository, but its not able to return is what i'm able to understand
This is my method in controller
public JsonResult GetAllCapacityData()
{
try
{
var data = _capacityService.GetAllData(null).ToList();
return Json(new
{
data = data
});
}
catch (Exception ex)
{
_logger.Error("WebApp -> AreaMappingController -> GetAllData -> Catch -> ", ex);
throw;
}
}
and this is my ajax request
$(document).ready(function() {
if ($('#loaderDiv').hasClass("show")) {
$('#loaderDiv').removeClass("show");
}
GetCapacityData();
});
function GetCapacityData() {
$('#personaliseDatatable').DataTable({
responsive: true,
processing: false,
serverSide: false,
searching: true,
scrollX: true,
bDestroy: true,
"scrollX": true,
aaSorting: [0, 'desc'],
ajax: {
url: '#Url.Action("GetAllCapacityData", "Capacity")',
type: 'POST'
},
language: {
search: "",
searchPlaceholder: "Search...",
sInfoFiltered: ""
},
columns: [{
"render": function(data, type, full, meta) {
return meta.row + 1;
}
},
{
data: "data.ZoneMaster.ZoneName"
},
{
data: "CateogoryName"
},
{
data: "SubCateogoryName"
},
{
data: "ServiceType"
},
{
data: "UserType"
},
{
data: "Division"
},
{
data: "SlotName"
},
{
data: "AllowBooking"
},
{
data: "HoursBlockAhead"
},
{
data: "DaysOpenAheadForBooking"
},
{
data: "MaximumOrderCapacity"
},
{
mRender: function(data, type, row) {
return '<a class="actionLinks" data-toggle="tooltip" title="View Details" style="cursor:pointer;" onclick="EditCapacity(' + row.CapacityPlannerId + ')">Edit</a>';
},
sortable: false,
searchable: false
}
]
});
alert(data.ZoneMaster.ZoneId);
}
And this my Datatable
<div class="card-body">
<table style="width:100%" class="table table-striped table-hover table-bordered" id="personaliseDatatable">
<thead>
<tr>
<th>#</th>
<th>Zone</th>
<th>Cateogory</th>
<th>Sub Cateogory</th>
<th>Service Type</th>
<th>User Type</th>
<th>Division</th>
<th>Slot Name</th>
<th>Allow Booking</th>
<th>Hours to Block Ahead</th>
<th>Days Open Ahead</th>
<th>Max. Order Capacity</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
Error on console
POST http://localhost:53201/Capacity/GetAllCapacityData 500 (Internal Server Error)
Any Help would be deeply appreciated

load json data in bootstrap data table

i created a table using html . now i want to populate my table using json data. i have been using the example https://www.youtube.com/watch?v=A20PY5RxdI8
my javascript code is here
$(document).ready(function () {
$.getJSON("my.php", function(json){
myjson = json;
}).done(function() {
$('#tble').bootstrapTable('load', myjson);
var $table = $('#tble');
$table.bootstrapTable('load', myjson);
$table.bootstrapTable({
search: true,
pagination: true,
buttonsClass: 'primaryt',
showFooter: true,
minimumCountColumns: 2,
columns: [ {
field: 'one',
title: 'ID'
}, {
field: 'two',
title: 'f name'
}, {
field: 'three',
title: 'last name'
}],
data: myjson
});
});
});
<table id = 'tble'>
<tr class=xl70 height=42 style='mso-height-source:userset;height:31.5pt'>
<th height=42 class=xl72 width=57 style='height:31.5pt;border-top:none;
border-left:none;width:43pt' data-field="one">1</th>
<th class=xl72 width=80 style='border-top:none;border-left:none;width:60pt'>2</th>
<th class=xl72 width=97 style='border-top:none;border-left:none;width:73pt'>3</th>
</tr>
</table>
i want to populate json into my table but it does not display any data in the said table
You can use the following code example:
$.getJSON("my.php")
.done(function(data) {
$('#tble').bootstrapTable('load', data);
})
Read the $.getJson() documentation for more example.
I have checked the documentation of Bootstrap table which you are using in your example.
The document is poorly written without explaining the parameters. Which results in confusion. When you read the document and do some JS fiddle you will realise that data-toggle attribute is very important. The value of this attribute should be the same as the Id of your table.
you can try removing data attribute filed in below fiddle to verify it.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/bootstrap-table#1.15.3/dist/bootstrap-table.min.css" rel="stylesheet">
<script src="https://unpkg.com/bootstrap-table#1.15.3/dist/bootstrap-table.min.js"></script>
<div id="toolbar">
<button id="button" class="btn btn-secondary">load</button>
</div>
<table
id="table"
data-toggle="table"
data-height="460">
<thead>
<tr>
<th data-field="id">ID</th>
<th data-field="name">Item Name</th>
<th data-field="price">Item Price</th>
</tr>
</thead>
</table>
<script>
var $table = $('#table')
var $button = $('#button')
function randomData() {
var startId = ~~(Math.random() * 100)
var rows = []
for (var i = 0; i < 10; i++) {
rows.push({
id: startId + i,
name: 'test' + (startId + i),
price: '$' + (startId + i)
})
}
return rows
}
$(function() {
var someData = randomData();
debugger;
$table.bootstrapTable('load', someData)
})
</script>
You will need to modify your code as below.
HTML
<table id = 'tble' data-toggle="tble">
<thead>
<tr>
<th data-field="one">ID</th>
<th data-field="two">f name</th>
<th data-field="three">last name</th>
</tr>
</thead>
</table>
and JS
$(document).ready(function () {
$('#table').bootstrapTable({
url: 'my.php',
pagination: true,
search: true,
columns: [{
field: 'one',
title: 'ID'
}, {
field: 'two',
title: 'f name'
}, {
field: 'three',
title: 'last name'
}]
})
});
Note: your URL should return a json response. Else instead of getJSON you can use $.ajax

How to get all checkbox values in cells

I have jQuery datatables with some checkboxes for granting privileges.
I need to get table values to a array. Please enlighten me about how to get checkbox states inside cells, not only the checked ones. Thank you.
My table
<table id="jqueryTable" name="tt" class="table table-striped table-bordered" cellspacing="0">
<thead>
<tr>
<th name="id">
ID
</th>
<th name="name">
PRIV_Name_Str
</th>
<th name="create">
Create
</th>
<th>
Edit
</th>
<th>
View
</th>
</tr>
</thead>
<table>
My datatable query
function LoadProduct(element) {
$.ajax({
url: '/ADM_MAS_Privilege/GetFormData',
data: { YourValue: $('#productCategory').val() },
method: 'post',
dataType: 'json',
success: function (data) {
var table = $('#jqueryTable').dataTable({
paging: true,
sort: true,
searching: true,
scrollY: 200,
data: data,
bDestroy: true,
"columnDefs":
[{
"targets": [2, 3, 4],
"render": function (data, type, row, meta) {
console.log("XX " + meta.row + " " + meta.col);
return type === 'display' ?
'<input type="checkbox" id="p" class="chk" name="group' + meta.row + '" /> ' + data :
data;
columns: [{ "data": "ID", "ID": "ID", "autoWidth": true },
{
"data": "PRIV_Name_Str", "PRIV_Name_Str": "PRIV_Name_Str", "autoWidth": true
},
{
"data": "Create", "Create": "Create", "autoWidth": true
},
{ "data": "Edit", "Edit": "Edit", "autoWidth": true },
{
"data": "View"
}
]
});
}
});
};
My jQuery function to read datatable
$('#upload').click(function () {
var table = document.getElementById("jqueryTable");
var tableArr = [];
for (var i = 1; i < table.rows.length; i++) {
tableArr.push({
ID: table.rows[i].cells[0].innerHTML,
PRIV_Name_Str: table.rows[i].cells[1].innerHTML,
Create: table.rows[i].cells[2].innerHTML,
Edit: table.rows[i].cells[3].innerHTML,
View: table.rows[i].cells[4].innerHTML
});
}
});
I tried table.rows[i].cells[2].innerHTML.getElementById("p").checked even and it's not working.
Since you are using jQuery:
document.getElementById("jqueryTable").each(function (index, element) {
tableArr.push({
ID: element.cells[0].innerHTML,
PRIV_Name_Str: element.cells[1].innerHTML,
Create: element.cells[2].innerHTML,
Edit: element.cells[3].innerHTML,
View: element.cells[4].innerHTML
})
})
You can find the element and the checked property within each cell:
for (var i = 1; i < table.rows.length; i++) {
var cells = table.rows[i].cells;
tableArr.push({
ID: cells[0].innerHTML,
PRIV_Name_Str: cells[1].innerHTML,
Create: cells[2].querySelectorAll('input')[0].checked,
Edit: cells[3].querySelectorAll('input')[0].checked,
View: cells[4].querySelectorAll('input')[0].checked
});
}

How to empty and refill jquery datatable?

I have a jquery datatable on my page. This datatable is gonna show data based on a request made to my api
The HTML that I have is like the following:
<table id="details" class="table table-bordered table-hover table-striped nowrap hidden display" cellspacing="0" width="100%">
<thead>
<tr>
<th> </th>
<th>Patient Full Name</th>
<th class="hidden">LF</th>
</tr>
</thead>
<tfoot>
<tr>
<th> </th>
<th>Patient Full Name</th>
<th class="hidden">LF</th>
</tr>
</tfoot>
<tbody>
<tr id="dummytr2"><td style="text-align:center;padding-top:20px;" colspan="7"><p><em>No Data Available</em></p></td></tr>
</tbody>
</table>
The first <th> is gonna be used to collapse the tr and get the facility (the third <th> or the hidden one) of this patient.
I have a dummy <tr> in the table because I don't want to initialize the datatable at the beginning so I don't get the error message that tells me that I can't initialize my datatable twice.
The request to my api is gonna be triggered through a bunch of buttons like the following:
$.ajax({
url: "https://" + window.myLocalVar + "/api/metrics/GetDetails?metricName=" + metric,
type: "GET",
dataType: 'json',
contentType: 'application/json',
success: function (requests) {
if (requests.length > 0) {
$("#dummytr2").remove();
for (var i = 0; i < requests.length; i++) {
var patient_name = requests[i].PatientFullName;
var lab_facility = requests[i].LabFacility;
tr = '<tr>\
<td class=" details-control"></td>\
<td>' + patient_name + '</td>\
<td class="hidden">' + lab_facility + '</td>\
</tr>';
$("#details > tbody").append(tr);
//click event for each tr
$('#details tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
}
}
// NOT SURE WHY IT IS NOT WORKING
$('#details').dataTable().fnDestroy();
var table = $('#details').DataTable({
"scrollX": true,
stateSave: true,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "PatientFullName" },
{ "data": "LabFacility" }
],
"order": [[1, 'asc']]
});
},
error: function (err) {
if (err) {
console.log(err);
}
}
});
});
function format(d) {
// `d` is the original data object for the row
var lf = d.LabFacility;
if (lf == "") {
lf = "No Lab Facility"
}
// wrapping text is not working???
return '<div class="table-responsive"><table class="table display" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Lab Facility:</td>' +
'<td>' + lf + '</td>' +
'</tr>' +
'</table></div>';
}
This ajax request is gonna get called each time a button is clicked. This means the content of my datatable is going to change each time a button was clicked. I tried to clear and refill it did not work.. I tried to destroy it .. it did not work.. each time I destroy my datatable and execute the script it won't change the content of the table.
I am not sure what's wrong with my code. My code works only for the first time.. the second time you click a button, it won't update my datatable.
Thanks!
You need to:
empty the table with empty()
remove $('#details').dataTable().fnDestroy();
add destroy: true option
For example:
if (requests.length > 0) {
// Empty table
$('#details').empty();
// ... skipped ...
var table = $('#details').DataTable({
destroy: true,
// ... skipped ...
});
// ... skipped ...
}
Please see sample of what I was saying in comments above:
var dataTable_ = null;
var init_ = false;
var initDataTable = function() {
dataTable_ = $('#table').DataTable({
preDrawCallback: function(settings) {
},
drawCallback: function(settings) {
if (init_ === false) {
init_ = true;
}
},
searching: true,
data: [],
fnCreatedRow: function(nRow, aData, iDataIndex) {
},
scrollY: true,
scrollX: true,
responsive: false,
serverSide: false,
autoWidth: false,
processing: false,
scrollCollapse: false,
lengthChange: false,
fixedColumns: false,
info: false,
select: {
info: false,
items: 'rows'
},
dom: '<"toolbar">Bfrtip',
orderMulti: false,
stripeClasses: ['dt-stripe-1', 'dt-stripe-2'],
columns: [{
name: 'test1',
data: 'test1',
title: 'Test1',
type: 'string',
orderable: true
},
{
name: 'test2',
data: 'test2',
title: 'Test2',
type: 'string',
orderable: true
},
]
});
};
var ajaxFunction = function() {
$.ajax({
url: "https://api.myjson.com/bins/7ed89",
type: "GET",
dataType: 'json',
contentType: 'application/json',
success: function(data) {
if (init_ === false) {
initDataTable();
}
if (typeof dataTable_ == 'object') {
dataTable_.rows().remove().draw();
dataTable_.rows.add(data);
dataTable_.draw();
}
//console.log(data);
}
});
};
$('#button').click(function() {
ajaxFunction();
});
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<table id="table" class="cell-border hover call-list">
</table>
<button id="button">Click To Load Data</button>

Categories

Resources