Search XML and display results using jQuery - javascript

I have multiple XML files which contain TV Listings each file is one TV channel. I want to be able to search by program title and display the results in a html table. So far I have been able to search by one XML file - so by one channel. I want to be able to search by multiple channels using user input via an input box and search button. The XML I have looks like:
<?xml version="1.0" encoding="UTF-8"?>
<channel id="sky_one" source="Sky" date="25/11/2014">
<programme>
<desc>Tony's motorcycle bursts into flames between his legs while town planner Liz is left in agony after her half-tonne horse bolts and lands on top of her. Also in HD</desc>
<title>The Real A & E</title>
<end>0630</end>
<start>0600</start>
</programme>
(only a snippet)
The jQuery that I have so far, which works for one channel looks like:
$(document).ready(function () {
//GLOBAL VAR
var keyword = '';
var pub = '';
var i = 0;
$("#searchButton").click(function () {
keyword = $("input#term").val();
//Reset any message
var errMsg = '';
pub = '';
if (keyword == '') {
errMsg += 'Please enter a search term';
} else {
searchThis();
}
if (errMsg != '') {
pub += '<div class="error">';
pub += errMsg;
pub += '</div>';
}
//Show error
$('#result').html(pub);
});
// ----------------------------------------- SKY NEWS -----------------------------------------------------------
function searchThis() {
$.ajax({
type: "GET",
url: "https://scm.ulster.ac.uk/~B00533474/workspace/COM554/assignment_2/CR/sky_one.xml",
dataType: "xml",
success: function (xml) {
loadPublication(xml)
}
});
}
function loadPublication(xmlData) {
i = 0;
var row;
var searchExp = "";
$(xmlData).find('programme').each(function () {
var title = $(this).find('title').text();
var desc = $(this).find('desc').text();
var start = $(this).find('start').text();
//Format the keyword expression
var exp = new RegExp(keyword, "gi");
//Match to Title of programme
searchExp = title.match(exp);
if (searchExp != null) {
//Start building the result
if ((i % 2) == 0) {
row = 'even';
} else {
row = 'odd';
}
i++;
pub += '<tr class="row ' + row + '">';
pub += '<td valign="top" class="col1">' + title + '</td>';
pub += '<td valign="top" class="col2">' + desc + '</td>';
pub += '<td valign="top" class="col3">' + start + '</td>';
pub += '</tr>' + 'n';
}
});
if (i == 0) {
pub += '<div class="error">';
pub += 'No Result was Found';
pub += '</div>' + 'n';
//Populate the result
$('#result').html(pub);
} else {
//Pass the result set
showResult(pub);
}
}
function showResult(resultSet) {
//Show the result
pub = '<div class="message">There are ' + i + ' results!</div>';
pub += '<table id="grid" class="table-bordered">';
pub += '<thead><tr>' + 'n';
pub += '<th class="col1"> </th>';
pub += '<th class="col2">Title</th>';
pub += '<th class="col3">Desc</th>';
pub += '<th class="col4">Start</th>';
pub += '</tr></thead>';
pub += '<tbody>';
pub += resultSet;
pub += '<hr class="horule" />';
pub += '</tbody>';
pub += '</table>';
//Populate
$('#result').html(pub)
}
});
And the html is as follows:
<input type="text" id="term" placeholder="Search by program title..."></div>
</div>
<input type="button" id="searchButton" value="Search" class="btn btn-primary" />
<div id="result"> </div>
I had an the idea of using the xml files as variables then using .when and .then to utilize the xml files, although I am not quite sure how to implement these, something like:
// Open the xml file
var sky1 = 'https://scm.ulster.ac.uk/~B00533474/workspace/COM554/assignment_2/CR/sky_one.xml',
bbc1 = 'https://scm.ulster.ac.uk/~B00533474/workspace/COM554/assignment_2/CR/bbc1.xml',
skyn = 'https://scm.ulster.ac.uk/~B00533474/workspace/COM554/assignment_2/CR/sky_news.xml';
$.when(
$.ajax( sky1 ),
$.ajax( bbc1 ),
$.ajax( skyn )
).then(function( skyone, bbcone, skynews ) {
var sky1p = $(skyone).find('programme'),
bbc1p = $(bbcone).find('programme'),
skynp = $(skynews).find('programme');
//sky one
sky1p.each(function() {
//DO Search
//sky one
skynp.each(function() {
//DO Search
//sky one
bbcp.each(function() {
//DO Search
The intended output is a html table with the title, description and program time. If anyone could help that would be great!

Related

Create menu by removing duplicates from JSON data

Build dynamic menu from multiple metadata files
I have a JavaScript loop that displays the images from an NFT collection and uses the class names to create a filter. Currently the filter menu is hard-coded, but I would like to build it dynamically from the metadata.
var loopFunction = function(dataIsLoading) { // the loop
let itemID = "";
var itemSource = "Azuki";
var itemURI = "https://ikzttp.mypinata.cloud/ipfs/QmQFkLSQysj94s5GvTHPyzTxrawwtjgiiYS2TBLgrvw8CW/"
for (let i = 0; i < 100; i++) {
itemID += [i];
$.getJSON(itemURI+i, function(data) {
// alert(data.name);
var eachItem = "";
var itemName = data.name;
var traits = data.attributes;
var classes = "";
var traitList = "";
$.each(data.attributes,function(index,entry) { // k (key), v (value) / i (index), e (entry)
var str = entry.value;
str = str.replace(/ /g, '');
classes += '' + entry.trait_type + '' + str + ' ';
traitList += '<span class="item-trait-type">' + entry.trait_type + ':</span> ' + str + '<br />';
});
eachItem += '<div class="cstm-grid-item cstm-width-1-2 cstm-width-large-1-3 cstm-width-x-large-1-4 ' +classes+'" id="'+i+'">';
eachItem += '<div class="img-placeholder">';
eachItem += '<img class="lazy" data-src="https://ikzttp.mypinata.cloud/ipfs/QmYDvPAXtiJg7s8JdRBSLWdgSphQdac8j1YuQNNxcGE1hg/'+i+'.png" width="100%" height="auto" />';
eachItem += '</div>';
eachItem += '<span class="item-title">'+itemName+'</span>';
eachItem += '<p class="item-traits">'
eachItem += traitList;
eachItem += '</p>'
eachItem += '</div>';
$('.cstm-grid').append(eachItem);
});
}
};
I have all of the data, but building the menu is difficult to do dynamically without the the menu having duplicate values. I just need the single base category (trait type) and the single values for that trait type. The final output should look something like:
<ul>
<li>
<h2>Trait Type 1</h2><!-- the category -->
<ul>
<li>red</li><!-- the value -->
<li>blue</li><!-- the value -->
</ul>
</li>
<li>
<h2>Trait Type 2</h2><!-- the category -->
<ul>
<li>sunglasses</li><!-- the value -->
<li>hat</li><!-- the value -->
</ul>
</li>
</ul>

javascript scripts not working in electron

I am trying to work on electron and made a simple dashboard GUI. i am a beginner in node js and electron.
Problem:
in my main gui.html: i have a table is being loaded, and from that table i need to select the rows from checklist for which i have made a js script:
script in read_checklist.js, this is taking the input checkbox element and selecting the whole row, which will later be shown after some processing in the textarea.
var checkboxes = document.getElementsByTagName("input");
var select_all = document.getElementById("allcb");
var warn_code = Array();
var family_array = Array();
var fail_drive_array = Array();
var waiverMap = {};
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = function() {
var currentRow = this.parentNode.parentNode;
var Warn_Code = currentRow.getElementsByTagName("td")[0];
var Family = currentRow.getElementsByTagName("td")[1];
var failing_drive = currentRow.getElementsByTagName("td")[3];
warn_code.push(Warn_Code.textContent);
family_array.push(Family.textContent);
fail_drive_array.push(failing_drive.textContent);
console.log('server started!' + currentRow );
alert(currentRow.textContent);
};
}
I am trying to import this in my gui.html like this:
This is where the table is getting displayed (code for this is below and it is stored in the renderer.js)
<!--This is for the table-->
<div id="data_lib" class="table-responsive">
</div>
<script type="text/javascript" src="./read_checklist.js"></script>
<!--This is for the table-->
My table is coming from another file, renderer.js
$(document).ready(function(){
var data;
$.ajax({
type: "GET",
url: "/Users/mrimat01/Desktop/CODE/electron_QAB_GUI_main/GUI/data.csv",
dataType: "text",
success: function(response)
{
data = $.csv.toArrays(response);
generateHtmlTable(data);
}
});
function generateHtmlTable(data) {
var html = "<table id='big_tables' class='table table-striped table-bordered' method='GET'>";
if(typeof(data[0]) === 'undefined') {
return null;
} else {
$.each(data, function( index, row ) {
//bind header
if(index == 0) {
html += '<thead>';
html += '<tr>';
$.each(row, function( index, colData ) {
html += '<th>';
html += colData;
html += '</th>';
});
html += '<th>';
html += "<input type='checkbox' id='allcb' name='allcb'/>Select";
html += '</th>';
html += '</tr>';
html += '</thead>';
html += '<tbody>';
} else {
html += '<tr>';
$.each(row, function( index, colData ) {
html += '<td>';
html += colData;
html += '</td>';
});
html += '<td>';
html += "<input id='name' type='checkbox' name='name' value='name' /> ";
html += '</td>';
html += '</tr>';
}
});
html += '</tbody>';
html += '</table>';
$('#data_lib').append(html);
}
}
});
I can see the table getting generated but read_checklist.js desn't work.
If i try to do the same thing in console, it works perfectly.
i have gone through many SO answers but couldn't seem to make this work.
Things i have tried:
making node_integration: true
using
module = undefined;}</script>
<script>if (window.module) module = window.module;</script>
adding the script directly below root <div>

i want to seperate a function into a multiple function jquery/ajax

I have a JavaScript file that has an Ajax function which calls a JSON file from an online server to extract it's data and interpret it in to a generated table... I want to separate the generate link, generate date, identify the car plate type/country into multiple functions that can be called by the ajax function.
// table of the server's data from JSON file
$(document).ready(function() {
$.ajax({
url: "http://127.0.0.1:3737/anpr?nb=0",
type: "GET",
dataType: "json",
success: function(data) {
var detection_data = '';
// generating the table to interpret the json data
$.each(data, function(key, value) {
detection_data += '<div class="table-row">';
detection_data += '<div class="serial">' + value.id + '</div>';
// identifie the car plate type/country fron json data
var plateType = value.plateType
if (plateType == "1") {
detection_data += '<div class="country">Tunisie TN</div>';
} else if (plateType == "2") {
detection_data += '<div class="country">Tunisie RS</div>';
} else if (plateType == "3") {
detection_data += '<div class="country">Tunisie GOV</div>';
} else if (plateType == "4") {
detection_data += '<div class="country">Lybie</div>';
} else if (plateType == "5") {
detection_data += '<div class="country">Algerie</div>';
} else {
detection_data += '<div class="country">Autre</div>';
}
detection_data += '<div class="visit">' + value.plateNumber + '</div>';
// generate date from json data
detection_data += '<div class="percentage">' + value.date.substr(8, 2) +
'/' + value.date.substr(5, 2) + '/' + value.date.substr(0, 4) +
' ' + value.date.substr(11, 2) + ':' + value.date.substr(14, 2) + ':' + value.date.substr(17, 2) + '</div>';
// generate link
detection_data += '<div>' + '<a class="img-pop-up" href="http://127.0.0.1:3737/anpr/snapshot?year=' + value.date.substr(0, 4) +
'&month=' + value.date.substr(5, 2) + '&day=' + value.date.substr(8, 2) +
'&&hour=' + value.date.substr(11, 2) + '&minute=' + value.date.substr(14, 2) + '&second=' + value.date.substr(17, 2) +
'&plate=' + value.plateNumber.split(" ").join("_") + '&platetype=' + value.plateType + '">link to picture</a>' + '</div>';
detection_data += '</div>';
});
$('#detection_table').append(detection_data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I tried to make your code more modular and readable. Here's what I could come up with. I am posting only relevant sections of your code to be concise.
NOTE: This is just a recommendation,I have not tested the below code.
var detection_data = '';
// generating the table to interpret the json data
$.each(data, function(key, value) {
detection_data += '<div class="table-row">';
detection_data += getPlateIDHTML(value.id);
// identifie the car plate type/country fron json data
detection_data += getPlateTypeCountryHTML(value.plateType);
// Plate number
detection_data += getPlateNumberHTML(value.plateNumber);
// generate date from json data
detection_data += getDetectionDateHtml(value.date);
// generate link
detection_data += getSnapshotLink(value.date, value.plateNumber, value.plateType);
detection_data += '</div>';
});
$('#detection_table').append(detection_data);
Below are my functions
String.prototype.format = function () {
var a = this, b;
for (b in arguments) {
a = a.replace(/%[a-z]/, arguments[b]);
}
return a; // Make chainable
};
function parseStringAsJSDate(date_as_string) {
return new Date(date_as_string);
}
function getPlateIDHTML(id) {
var plate_id_html = '<div class="serial">%s</div>';
return plate_id_html.format(id);
}
function getPlateNumberHTML(plateNumber) {
var plate_number_html = '<div class="visit">%s</div>';
return plate_number_html.format(plateNumber);
}
function getPlateTypeCountryHTML(plateType) {
var plateTypeCountry = {
"1": "Tunisie TN",
"2": "Tunisie RS",
"3": "Tunisie GOV",
"4": "Lybie",
"5": "Algerie",
};
var plate_type_country_html = '<div class="country">%s</div>';
if(plateType in plateTypeCountry) {
return detection_data_html.format(plateTypeCountry[plateType]);
} else {
return detection_data_html.format("Autre");
}
}
function getDetectionDateHtml(captured_date_as_string) {
var date_of_capture_html = '<div class="percentage">%s/%s/%s %s:%s:%s</div>';
var captured_date = parseStringAsJSDate(captured_date_as_string);
return date_of_capture_html.format(captured_date.getDate(), captured_date.getMonth()+1, captured_date.getFullYear(), captured_date.getHours(), captured_date.getMinutes(), captured_date.getSeconds());
}
function getSnapshotLink(captured_date_as_string, plateNumber, plateType) {
var snapshot_link = "http://127.0.0.1:3737/anpr/snapshot?year=%s&month=%s&year=%s&day=%s&hour=%s&minute=%s&second=%s&plate=%s&platetype=%s";
var snapshot_link_html = '<div><a class="img-pop-up" href="%s">Link to picture</a></div>';
var captured_date = parseStringAsJSDate(captured_date_as_string);
var snapshot_link = snapshot_link.format(captured_date.getDate(), captured_date.getMonth()+1, captured_date.getFullYear(), captured_date.getHours(), captured_date.getMinutes(), captured_date.getSeconds(), plateNumber.split(" ").join("_"), plateType);
return snapshot_link_html.format(snapshot_link);
}
Below is a brief explanation of each function
String.prototype.format: This is an equivalent of the old-school printf in C. I find variable-substitutions of the sort '<div class="serial">'+ id +'</div>' inter-mingling HTML with JavaScript very difficult to read. And therefore this.
parseStringAsJSDate: I assume that your API is under your control. I recommend you to modify the date format to ISO8601 so that it can be parsed by JavaScript as a Date. Your substr function again affects readability.
getPlateIDHTML & getPlateNumberHTML: Simple functions that just use the format function to embed the passed variables into the HTMLs to show ID and plate number.
getPlateTypeCountryHTML: I used a Python object here to reduce the number of ifs and else ifs.
getDetectionDateHtml & getSnapshotLink: I have tried to parse the date as a JavaScript date and this eliminates the substrs. Moreover, the use of format simplifies these functions further.
Let me know your suggestions on this. Suggestions/Criticism from Stack's gurus are more than welcome :)
UPDATE
Please check my updated format function. I sourced it from this excellent answer. Apologies, the earlier one was just copy-pasted, I should have tried it. Please just the format function to the one that's indicated and let me know

Sorting &Pagination for html table

Am using this Json to Html table and am getting the values also. All I need to do is implement sorting for this. Can someone help me out?
where in the objArray am passing my Json data.
All I need to do is implement Sorting and pagination. Please help me out.
function CreateTableViewX(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
for (var index in array[i]) {
str += '<td>' + array[i][index] + '</td>';
}
str += '</tr>';
}
str += '</tbody>'
str += '</table>';
return str;
}
Try Jquery datatable
All you need is to refer Jquery and datables Script files in your solution, select your html table using an Id or class name and Initialize it like this. Datatable will then take care of sorting and pagination for you.
$(document).ready(function(){
$('#tableID').dataTable();
});

onclick call to function from submit input not working

Here is my submit button written dynamically through AJAX:
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
}
htmlpage += "<div>"
htmlpage += "</ul>";
I am trying to rerun the updatefilters() function to change the items that are displayed. I imagine its a bit tough to conceptualize without seeing all the code...but essentially, all I need to do is run the function again on each click of the submit button...right now, its giving me a updatefilters is undefined error in firebug.
Heres my whole JS for reference
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters
});
getactivesession();
function getactivesession(ev, ui){
var i = 0;
var actfilter, strfilter;
var strfilterarray = new Array();
$.ajaxSetup({cache: false})
$.ajax({
type: "POST",
async: false,
url: 'welcome/getactivesession',
dataType: 'json',
success: function (data){
strfilter = JSON.stringify(data)
strfilterarray = strfilter.split(',')
for (i=0 ; i < strfilterarray.length ; i++) {
strfilter = strfilterarray[i]
strfilter = strfilter.replace(/[\[\]'"]+/g,'');
var strfilterdash = strfilter.replace(/\s+/g, '-')
actfilter = '#'+ strfilterdash
$(actfilter).addClass('ui-selected')
}
updatefilters();
}
});
}
function updatefilters(ev, ui){
// get the selected filters
var template, html;
var i = 0;
var page;
if(! page){
page = 0;
}
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
async: false,
url: 'welcome/updatefilters',
dataType: 'json',
data: { filters: filters, page: page },
success: function(data){
var html = "";
html += "<div id=board>"
html += "<div class='board' id='table'>"
html += "<div id='row'>header here</div>"
var pages = Math.ceil(data['num_threads']/10);
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
}
htmlpage += "<div>"
htmlpage += "</ul>";
htmlpage += "</br>";
html += htmlpage;
for (i=0 ; i < data['threads'].length ; i++)
{
html += "<div id=row>";
html += " <div id='author' style='background: url("+data['threads'][i].location + ") no-repeat; background-position: center;'><p>"+data['threads'][i].username + "</p></div>";
html += " <div id='arrow'></div>";
html += " <div id='subject' title='"+ data['threads'][i].body +"'>";
html += " "+ data['threads'][i].subject +"<p>Created: "+data['threads'][i].posttime+"</p></div>";
html += " <div id='info'>";
html += " <div id='replies'>" + data['threads'][i].replies_num + "</div>";
html += " <div id='lastpost'>"+ data['threads'][i].lastreply+"</div>";
html += " </div>";
html += "</div>";
}
html += "</div></div>";
$('#board').html(html);
}
});
}
});
There appears to be a few problems with this approach.
First, you're not actually calling the function in your onclick handler.
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
should be:
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters();' /></li"
Second, the updatefilters function isn't accessible from the global scope, which is where that anonymous function will be executed from. You'd have to move function updatefilters(ev, ui) outside the onload callback, perhaps to the top of your script block.

Categories