Ajax search with pagination.js and/or PHP - javascript

I want to do a search that can be triggered by given a specific URL (I tried with ajax and javascript here but im happy with a php variant also). I have 2 requirement phases (both should be displayed with pagination.js):
When I access eg.: https://<.myDomain.>/search/234x15 to put
the value inside the input and the filter automatically or make the
search over the whole database.
When I would go to eg.: https://<.myDomain.>/search I want to make POST search over the whole database.
My general problem is that I cannot include MySQL or other databases, I am limited to either JSON or objects/arrays (JS/php).
With my current solution processing 900 items using a big JSON file gets me a response after 5-8 seconds which is too long. And I will need to fill in with at least 3500 items.
Here is the solution I made:
<script>
var currentKeywords = $(location).attr('pathname');
var currentKeywordsFiltered = currentKeywords.replaceAll('+',' ');
const toBeSearched = currentKeywordsFiltered.split('/')[2];
$('#search-input').attr('value', toBeSearched);
var myArray = <?php echo json_encode($products_merged) ?>;
$(document).ready(function(){
console.log('Url keyword: ', toBeSearched);
var data = searchTable(toBeSearched, myArray);
buildTable(data);
(function(name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: data,
locator: 'dataSource',
totalNumber: 50,
pageSize: 20,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function() {
container.prev().html('Loading...');
}
},
callback: function(response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '';
$.each(response, function (index, dataSource) {
dataHtml +=
'<div style="border: 1px solid #888888; border-radius: 5px; margin: 15px;" class="col-md-2">'
+ '<div class="card-body">'
+ '<b>'+ dataSource.title +'</b></h5>'
+ 'Vezi specificatii'
+ '</div>'
+ '</div>';
});
dataHtml += '';
container.prev().html(dataHtml);
}
})
})('demo');
});
$('#search-input').on('keyup', function(){
var value = $(this).val();
console.log('value: ', value);
var data = searchTable(value, myArray);
buildTable(data);
(function(name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: data,
locator: 'dataSource',
totalNumber: 50,
pageSize: 20,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function() {
container.prev().html('Loading data from db...');
}
},
callback: function(response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '';
$.each(response, function (index, dataSource) {
dataHtml +=
'<div style="border: 1px solid #888888; border-radius: 5px; margin: 15px;" class="col-md-2">'
+ '<div class="card-body">'
+ '<b>'+ dataSource.title +'</b></h5>'
+ 'Vezi specificatii'
+ '</div>'
+ '</div>';
});
dataHtml += '';
container.prev().html(dataHtml);
}
})
})('demo');
});
$(function(){
if(toBeSearched === undefined){
buildTable(myArray);
(function(name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: myArray,
locator: 'dataSource',
totalNumber: 50,
pageSize: 20,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function() {
container.prev().html('Loading...');
}
},
callback: function(response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '';
$.each(response, function (index, dataSource) {
dataHtml +=
'<div style="border: 1px solid #888888; border-radius: 5px; margin: 15px;" class="col-md-2">'
+ '<div class="card-body">'
+ '<b>'+ dataSource.title +'</b></h5>'
+ 'Vezi specificatii'
+ '</div>'
+ '</div>';
});
dataHtml += '';
container.prev().html(dataHtml);
}
})
})('demo');
}
});
function searchTable(value, data){
var filteredData = [];
for(var i = 0; i < data.length; i++){
value = value.toLowerCase();
var name = data[i].title.toLowerCase();
if(name.includes(value)){
filteredData.push(data[i])
}
}
return filteredData;
}
function buildTable(data){
var table = document.getElementById('myTable');
table.innerHTML = '';
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].title}</td>
<td></td>
<td></td>
</tr>`;
table.innerHTML += row;
}
};
</script>
My question would be which architectural solutions i could go towards or how can I improve my code so it can be more efficient.
PS: I tried doing it first with php submission by grabbing the url and I was ending up in infinite loop using header on processing page.

Related

form not clearing properly after submit and also for hidden input

I'm using a parsley validator and somehow it affects my form. After submission, it won't clear all the inputs; especially hidden inputs. And when I tried to set some input value from javascript it won't show up.
I think it's because of my <form method="post" id="transaction_form">. I've tried to re-evaluate my HTML but still, it won't work properly.
$(document).ready(function () {
$("#cust_num").val(55555);
var exam_num = 12345;
var prod_num = 88998;
var prod_name = "Hello";
var prod_price = 150000;
var transactionTable = $("#transaction_table");
var trxprodcount = 0;
var subTotal = 0;
var endTotal = 0;
function clearinput() {
$("#transaction_form")[0].reset();
$("#transaction_form").parsley().reset();
//$('#get_productdata').attr('disabled', 'disabled');
$("#subtotal").html(0);
$("#endtotal").html(0);
}
clearinput();
function recount() {
subTotal = transactionTable.DataTable().column(3).data().sum();
$("#subtotal").html(subTotal);
endTotal = subTotal - (subTotal * $("#trx_disc").val()) / 100;
$("#endtotal").html(endTotal);
}
transactionTable.DataTable({
ordering: false,
responsive: true,
searching: false,
paging: false,
info: false,
fnRender: function (Obj) {
return "Rp" + Obj.Data[3];
},
drawCallback: function () {
recount();
},
});
$("#trx_disc").on("change", function () {
recount();
});
trxprodcount = trxprodcount + 1;
var exam_num = $("#cust_num").val() + "S" + trxprodcount;
var col_exam_num =
exam_num +
'<input type="hidden" name="hidden_exam_num[]" id="exam_num' +
trxprodcount +
'" class="exam_num" value="' +
exam_num +
'" />';
var col_exam_prod =
prod_num +
'<input type="hidden" name="hidden_exam_prod[]" id="exam_prod' +
trxprodcount +
'" value="' +
prod_num +
'" />';
var del_btn =
'<button type="button" name="del_prodtrx" id="' +
trxprodcount +
'" class="btn btn-danger btn-sm del_prodtrx" >Delete</button>';
transactionTable
.DataTable()
.row.add([col_exam_num, col_exam_prod, prod_name, prod_price, del_btn])
.draw()
.node();
$("#transaction_table").on("click", ".del_prodtrx", function () {
var row = $(this).parents("tr");
if ($(row).hasClass("child")) {
transactionTable.DataTable().row($(row).prev("tr")).remove().draw();
} else {
transactionTable.DataTable().row($(this).parents("tr")).remove().draw();
}
});
$("#transaction_form").on("submit", function (event) {
event.preventDefault();
if ($("#transaction_form").parsley().isValid()) {
var count_data = 0;
$(".exam_num").each(function () {
count_data = count_data + 1;
});
if (count_data > 0) {
clearinput();
} else {
$("#message").html(
'<div class="alert alert-danger">Customer/Product Kosong'
);
}
setTimeout(function () {
$("#message").html("");
}, 3000);
}
});
});
Live Example: https://jsfiddle.net/azissofyanp/9p7j1d6u/30/
And I'm very confused about it.

Pass JSON result from AJAX to HTML

I am querying a fuseki server using AJAX and the result that I am getting is a JSON object.
I would like to use pagination to go through the result with a limit of records per page. I have tried to send the JSON object to a div in the html file but it is not working. Is there a workaround this? Here is my code:
function myCallBack2(data) {
var all_results = '';
for (var i = 0; i < data.results.bindings.length; i++) {
var bc = '';
if (i % 2 == 0) {
bc = '#b8cddb';
} else {
bc = '#f2f5f7';
}
all_results += '<div class="all_results" style="background-color:' + bc + '">';
for (var j = 0; j < data.head.vars.length; j++) {
var text = data.results.bindings[i][data.head.vars[j]].value;
var type = data.results.bindings[i][data.head.vars[j]].type;
all_results += '<div class="result_row">';
if (type == ('literal')) {
all_results += '<p> ' + data.head.vars[j] + ": " + text + '</p>';
} else {
all_results += '<a href=' + text + " title=" + data.head.vars[j] + '>' + text + '</a>';
}
all_results += '</div>';
}
all_results += '</div>';
}
$('#result').html(all_results);
}
function doSparql() {
var myEndPoint = "http://localhost:3030/Test/query";
name = document.getElementById("search").value;
var requiredName = "?Author foaf:firstName \"" + name + "\".}";
myQuery = ["PREFIX dcterms: <http://purl.org/dc/terms/>",
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
"PREFIX locah: <http://data.archiveshub.ac.uk/def/>",
"SELECT ?Register ?Id ?Date ?Type",
"WHERE{",
"?Register dcterms:creator ?Author.",
"?Register dcterms:identifier ?Id.",
"?Register dcterms:type ?Type.",
"?Register locah:dateCreatedAccumulatedString ?Date.",
requiredName
].join(" ");
console.log('myQuery: ' + myQuery);
window.alert(myQuery);
$.ajax({
dataType: "jsonp",
url: myEndPoint,
data: {
"query": myQuery,
"output": "json"
},
success: myCallBack2,
error: myError
});
console.log('After .ajax');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//raw.github.com/botmonster/jquery-bootpag/master/lib/jquery.bootpag.min.js"></script>
<div id="page-selection1" "></div>
<div id="result " class="result "></div>
<div id="page-selection2 "></div>
<script>
$('#page-selection1,#page-selection2').bootpag({
total: 50,
page: 1,
maxVisible: 5,
leaps: true,
firstLastUse: true,
first: 'First',
last: 'Last',
wrapClass: 'pagination',
activeClass: 'active',
disabledClass: 'disabled',
nextClass: 'next',
prevClass: 'prev',
lastClass: 'last',
firstClass: 'first'
}).on("page ", function(event, num) {
$("#result ").html("Page " + num);
});
</script>
I am expecting to show part of the results instead Page 1, Page 2... in #result according to a limit per page.

Display data in Div from json in jquery

I have data in a json using ajax code. Now I want to display data in a div Below is the code which I bring
{
"Table":[
{
"APP_MST_ID":321.0,
"APPLICATIONNAME":"R-Locator for Enterprise",
"PROJECTNO":"R4G-25-APD-006",
"VSS_FOLDER_LOC":null,
"CAT_ID":1.0,
"SPOC_APPUSRID":79.0,
"SUPPORT_TEAM":"0",
"REQUESTED_BY_APPUSRID":51.0,
"DELIVERY_MANAGER_APPUSRID":43.0,
"CREATEDBY_APPUSRID":null,
"CREATEDDATE":null,
"MODIFIEDBY_APPUSRID":null,
"MODIFIED_DATE":null,
"APPIMAGEPATH":null,
"PARENT_APP_ID":null,
"SERVER_LOCATION":null,
"USAGE_CATID":null
}
]
}
and the div.
<div id="dvTable">
</div>
And for bringing the data below is the code.
function SearchInfo() {
var textBoxValue = $('#addresSearch').val();
$.ajax({
type: "POST",
url: "http://localhost:11181/Search/GetFilterSearch",
data: JSON.stringify({ textBoxValue: textBoxValue }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
// display data in div here
}
})
}
Now how should I display that data which is in json in a div and show it.
You can loop like:
$(document).ready(function(){
/*
var r = {
"Table":[
{
"APP_MST_ID":321.0,
"APPLICATIONNAME":"R-Locator for Enterprise",
"PROJECTNO":"R4G-25-APD-006",
"VSS_FOLDER_LOC":null,
"CAT_ID":1.0,
"SPOC_APPUSRID":79.0,
"SUPPORT_TEAM":"0",
"REQUESTED_BY_APPUSRID":51.0,
"DELIVERY_MANAGER_APPUSRID":43.0,
"CREATEDBY_APPUSRID":null,
"CREATEDDATE":null,
"MODIFIEDBY_APPUSRID":null,
"MODIFIED_DATE":null,
"APPIMAGEPATH":null,
"PARENT_APP_ID":null,
"SERVER_LOCATION":null,
"USAGE_CATID":null
}
]
};
*/
//Empty rows
var r = {
"Table":[]
};
var html = '';
//Check if has data
if ( r.Table.length !== 0 ) {
html += '<table>';
for ( var key in r.Table ) {
var row = r.Table[key];
//For the header
if ( key == 0 ) {
html += '<tr>';
for ( var key2 in row ) {
html += '<th>';
html += key2;
html += '</th>';
}
html += '</tr>';
}
html += '<tr>';
for ( var key2 in row ) {
html += '<td>';
html += row[key2];
html += '</td>';
}
html += '</tr>';
}
html += '</table>';
} else {
//No data.
html += "No data.";
}
$( "#dvTable" ).html( html );
//console.log();
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="dvTable"></div>
var table = $('#table_id');
for (i = 1; i < data.length; i++) {
table.append('<tr>');
table.find('tr:last-child').append(
'<td>' + data[i]["APP_MST_ID"] + '</td>',
'<td>' + data[i]["APPLICATIONNAME"] + '</td>'
);
}
<table class="GeneratedTable" align="center" id = "table_id">
<tr>
<th>APP_MST_ID</th>
<th>APPLICATIONNAME</th>
</tr>
</table>
This is one of a lot of possible answers. You can do it even with Object.keys, concatenating with DOM functions...
let response = {
"Table":[
{
"APP_MST_ID":321.0,
"APPLICATIONNAME":"R-Locator for Enterprise",
"PROJECTNO":"R4G-25-APD-006",
"VSS_FOLDER_LOC":null,
"CAT_ID":1.0,
"SPOC_APPUSRID":79.0,
"SUPPORT_TEAM":"0",
"REQUESTED_BY_APPUSRID":51.0,
"DELIVERY_MANAGER_APPUSRID":43.0,
"CREATEDBY_APPUSRID":null,
"CREATEDDATE":null,
"MODIFIEDBY_APPUSRID":null,
"MODIFIED_DATE":null,
"APPIMAGEPATH":null,
"PARENT_APP_ID":null,
"SERVER_LOCATION":null,
"USAGE_CATID":null
}
]
}
for(let k in response.Table[0]){
window.document.getElementById("dvTable").innerHTML+=`<div>${response.Table[0][k]}</div>`;
}
<div id="dvTable">
</div>
This could be a possible solution.
var json = '{"Table": [{"APP_MST_ID": 321.0,"APPLICATIONNAME": "R-Locator for Enterprise","PROJECTNO": "R4G-25-APD-006","VSS_FOLDER_LOC":null,"CAT_ID":1.0,"SPOC_APPUSRID":79.0,"SUPPORT_TEAM":"0","REQUESTED_BY_APPUSRID":51.0,"DELIVERY_MANAGER_APPUSRID":43.0,"CREATEDBY_APPUSRID": null,"CREATEDDATE": null,"MODIFIEDBY_APPUSRID": null,"MODIFIED_DATE": null,"APPIMAGEPATH": null,"PARENT_APP_ID": null,"SERVER_LOCATION": null,"USAGE_CATID": null}]}';
var objects = JSON.parse(json); // Parse the json
objects = objects.Table; // Get the content of Table
var string = ""; // create a string
jQuery.each(objects[0], function(id, value) { // get all the id's and values
string = string + value + " "; // Do something here with the values or id's
});
// create something where you add it, or do it inside the each()-function
var div = document.createElement('div');
div.innerHTML = string;
document.body.appendChild(div);
// ^ just to show the values in this example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You could just dump your formatted data to the div but as its difficult to replicate an $.ajax call I have commented out those parts.
It would work something like this:
var r =
`{
"Table": [{
"APP_MST_ID": 321.0,
"APPLICATIONNAME": "R-Locator for Enterprise",
"PROJECTNO": "R4G-25-APD-006",
"VSS_FOLDER_LOC": null,
"CAT_ID": 1.0,
"SPOC_APPUSRID": 79.0,
"SUPPORT_TEAM": "0",
"REQUESTED_BY_APPUSRID": 51.0,
"DELIVERY_MANAGER_APPUSRID": 43.0,
"CREATEDBY_APPUSRID": null,
"CREATEDDATE": null,
"MODIFIEDBY_APPUSRID": null,
"MODIFIED_DATE": null,
"APPIMAGEPATH": null,
"PARENT_APP_ID": null,
"SERVER_LOCATION": null,
"USAGE_CATID": null
}]
}`;
function SearchInfo() {
//var textBoxValue = $('#addresSearch').val();
//$.ajax({
// type: "POST",
// url: "http://localhost:11181/Search/GetFilterSearch",
// data: JSON.stringify({
// textBoxValue: textBoxValue
// }),
// contentType: "application/json; charset=utf-8",
// dataType: "json",
// success: function(r) {
// display data in div here
$("#dvTable").html("<pre>" + r + "</pre>")
// }
//})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="SearchInfo();">Search</button>
<div id="dvTable"></div>
If you are looking for an actual table then this is how you would do it:
var r = {
"Table": [{
"APP_MST_ID": 321.0,
"APPLICATIONNAME": "R-Locator for Enterprise",
"PROJECTNO": "R4G-25-APD-006",
"VSS_FOLDER_LOC": null,
"CAT_ID": 1.0,
"SPOC_APPUSRID": 79.0,
"SUPPORT_TEAM": "0",
"REQUESTED_BY_APPUSRID": 51.0,
"DELIVERY_MANAGER_APPUSRID": 43.0,
"CREATEDBY_APPUSRID": null,
"CREATEDDATE": null,
"MODIFIEDBY_APPUSRID": null,
"MODIFIED_DATE": null,
"APPIMAGEPATH": null,
"PARENT_APP_ID": null,
"SERVER_LOCATION": null,
"USAGE_CATID": null
}]
};
function SearchInfo() {
//var textBoxValue = $('#addresSearch').val();
//$.ajax({
// type: "POST",
// url: "http://localhost:11181/Search/GetFilterSearch",
// data: JSON.stringify({
// textBoxValue: textBoxValue
// }),
// contentType: "application/json; charset=utf-8",
// dataType: "json",
// success: function(r) {
// display data in div here
$("#dvTable").html(CreateTable(r).html())
// }
//})
}
function CreateTable(data) {
var data = data.Table;
var table = $("<table><tr /></table>");
$.each(data[0], function(key, value) {
table.find("tr").append("<th>" + key + "</th>");
});
$.each(data, function() {
var trHtml = $("<tr />");
$.each(this, function(key, value) {
trHtml.append("<td>" + value + "</td>");
});
table.append(trHtml);
});
return table;
}
th,
td {
border: solid 1px black;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="SearchInfo();">Search</button>
<div id="dvTable"></div>
There are multiple ways, one of them is put a table tag in your div and append rows in it, like:
$.each(r,function(index,value){
var html = '<td>'+
'<tr>'+value.APP_MST_ID+'</tr>'+
'<tr>'+value.APPLICATIONNAME+'</tr>'+
'<tr>'+value.PROJECTNO+'</tr>'+
'<tr>'+value.VSS_FOLDER_LOC+'</tr>'+
'<tr>'+value.CAT_ID+'</tr>'+
'<tr>'+value.SPOC_APPUSRID+'</tr>'+
'<tr>'+value.SUPPORT_TEAM+'</tr>'+
'<tr>'+value.REQUESTED_BY_APPUSRID+'</tr>'+
'<tr>'+value.DELIVERY_MANAGER_APPUSRID+'</tr>'+
'<tr>'+value.CREATEDBY_APPUSRID+'</tr>'+
'<tr>'+value.CREATEDDATE+'</tr>'+
'<tr>'+value.MODIFIEDBY_APPUSRID+'</tr>'+
'<tr>'+value.MODIFIED_DATE+'</tr>'+
'<tr>'+value.APPIMAGEPATH+'</tr>'+
'<tr>'+value.PARENT_APP_ID+'</tr>'+
'<tr>'+value.value.SERVER_LOCATION+'</tr>'+
'<tr>'+value.USAGE_CATID+'</tr>'+
'</td>'
$('#table_id').append(html);
})
and so on. and you can data format as you want.

LocalStorage : Row Table not display when page reloaded

Good Morning.
I already store table into localStorage.
but when im reload the page, The Row in the Default Table not displaying.
and if i'm disable initialization it's will be working fine,
but not when i'm Add new table, The Default Table will not displayed when page reloaded :
// Defaul Table
$("#mainTable").dataTable({
"ajax": "https://api.myjson.com/bins/1hes6z",
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
});
/* CREATE TABLE FITURE */
$('.submitButton').click(function() {
function getTableList() {
var addTable = '<div class="tab-pane" id="folder' + localStorage.Index + '">' +
'<div class="zf-table">' +
'<table id="table' + localStorage.Index + '" class="table table-bordered table-hover myFade dynamicTable">' +
'<thead>' +
'<tr>' +
'<th style="border-color:rgb(221, 221, 221);"> </th>' +
'<th>Audience Name</th>' +
'<th>Type</th>' +
'<th>Size</th>' +
'<th>Date Created</th>' +
'<th>Action</th>' +
'</tr>' +
'</thead><tbody></tbody>' +
'</table>' +
'</div>' +
'</div>';
return addTable;
}
if (true) {
/** INDEX FOR INCREMENT ID **/
if (typeof(Storage) !== "undefined") {
if (localStorage.Index) {
localStorage.Index = Number(localStorage.Index) + 1;
} else {
localStorage.Index = 1;
}
} // if storage
var resultTable = JSON.parse(localStorage.getItem("tableList"));
if (resultTable == null) {
resultTable = [];
}
let newtableHTML = getTableList();
resultTable.push({
table: newtableHTML
});
// save the new resultFolder array
localStorage.setItem("tableList", JSON.stringify(resultTable));
/* append Table baru */
$('.tab-content').append(newtableHTML);
var newTable = $("#table" + localStorage.Index).dataTable();
alert("sucess create table");
} else {
alert("Failed create Table");
}
}); // submitButton func
//on init fill the table-content
$(document).ready(function() {
$("#mainTable").dataTable();
var resultTable = JSON.parse(localStorage.getItem("tableList"));
if (resultTable != null) {
//get the nav reference in DOM
let tableContent = $(".tab-content");
//clear the html contents
tableContent.html('');
for (var i = 0; i < resultTable.length; i++) {
var items = resultTable[i];
$(".tab-content").append(items.table);
}
$(".dynamicTable").dataTable();
} else {
let inititalTable = [];
inititalTable.push({
table: $('div.tab-content').html()
});
localStorage.setItem("tableList", JSON.stringify(inititalTable));
}
});
How to display the row table when page reloaded without deleting initialTable code?
JSFiddle Demo

.replacewith not working when called a second time

I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);

Categories

Resources