Reading in a specific csv file into html - javascript

I'm currently trying to select a specific csv file based on user selection and then display this as a html table in the web page on the click of a button.
The steps that this will need to have are:
to select the options from a drop down which will be used to identify the csv file name
pass the csv file name to a function which displays this as a html table
perform this on the click of a button rather than when the web page loads
Below is the code I have so far, the first part of the code identifies the csv file name.
The second part reads in a hard coded csv file and parses it as a html table which is displayed when the web page opens.
<script>
function button_clicked(){
var obj_opt = document.getElementById("opt");
var opt = obj_opt.value;
if (opt==""){
alert("Please select Option1");
return;
}
var obj_opt_two = document.getElementById("opt_two");
var opt_two = obj_opt_two.value;
if (opt_two==""){
alert("Please select Option2");
return;
}
var urls= "http://mysite/" + opt + "_" + opt_two + ".csv";
alert("The link is: " + urls);
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<script>
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "http://mysite/Option1_Option2.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
</script>
<button type="button" onClick="button_clicked()">Load New File</button>
I am unsure how to combine the two javascripts to load the user selected csv as a table via a button, any help on how to do this would be greatly appreciated!

To make this work you need to move the $.ajax logic in to the button click handler, and apply the url value to it.
Also note that using on* event attributes in HTML is very outdated and should be avoided where possible. You should use unobtrusive event handlers instead. As you've already included jQuery in the page, you can use that:
$(function() {
$('#load').click(function() {
var opt = $("#opt").val();
if (!opt) {
alert("Please select Option1");
return;
}
var opt_two = $("#opt_two").val();
if (!opt_two) {
alert("Please select Option2");
return;
}
$.ajax({
type: "GET",
url: `http://mysite/${opt}_${opt_two}.csv`,
success: function(data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
});
function arrayToTable(tableData) {
var html = tableData.map(function(row) {
var rowHtml = '<tr>';
row.forEach(function(cell) {
rowHtml += `<td>${cell}</td>`;
});
return rowHtml + '</tr>';
});
return `<table>${html.join('')}</table>`;
}
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<button type="button" id="load">Load New File</button>
Finally, note that jQuery 1.7 is rather old now. I'd suggest upgrading to 1.12 if you still need to support older IE browsers, or 3.2.1 if not.

Move the
$.ajax({
type: "GET",
url: "http://mysite/Option1_Option2.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
in the place of
alert("The link is: " + urls);

Related

Replace table instead of append jquery

I have the following code segment that grabs user input from an HTML form, and then reads a CSV file, and grabs corresponding data to display to my website. If I submit another 'searchTerm' after the initial one in my form, it appends the new row of data from the csv file to the page, and I want it to replace instead. When I try to replace the row however, all my data vanishes.
function submitForm(){
nameValue = document.getElementById("searchTerm").value;
//document.getElementById("display-results").innerHTML = nameValue;
location.href = "#page-3";
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
if (cellData == nameValue) {
row.append($('<td>'+rowData[1]+'</td>'));
}
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "mainFile.csv",
success: function (data) {
parsed = Papa.parse(data).data;
$('#display-results').append(arrayToTable(Papa.parse(data).data));
}
});
}
As you can see in the image, it appends the content rather than replacing the first array.
Remember to just replace the table, not the entire display-results element (except the first time you build the table).
if($('#display-results table').length === 0) // append if you haven't built the table yet
$('#display-results').append(arrayToTable(Papa.parse(data).data));
else
$('#display-results table').replaceWith(arrayToTable(Papa.parse(data).data));

Redirect to URL in json response

I have two files fetch.php and index.php. The fetch.php file does a search and converts the results to Json.
Index.php has Jquery which loops through the Json result. One of the cells contains a URL. How can I get a user to redirect to the URL.
//index.php==============================
<script>
$(document).ready(function(){
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
$('#total_records').text(data.length);
var html = '';
if(data.length > 0)
{
for(var count = 0; count < data.length; count++)
{
html += '<hr>';
html += '<tr>';
html += '<div>'+data[count].title+'</div>';
html += '<td>'+data[count].book+'</td><tr/>';
html += '<br/><td>'+data[count].description+'</td><tr/>';
html += '<td><button> VIEW </button> '+data[count].url+'</td>'; //Is there a way to redirect to this URL by clicking on the VIEW button
html += '<hr>';
}
}
else
{
html = '<tr><td colspan="5">No Data Found</td></tr>';
}
$('tbody').html(html);
}
})
}
$('#search').click(function(){
var query = $('#search_id').val();
load_data(query);
});
</script>
Simple solution:
html += '<td><button onclick="window.location.href=\''+data[count].url+'\'"> VIEW </button> '+data[count].url+'</td>';
Consider the following suggestions:
$(function() {
function load_data(q) {
$.ajax({
url: "fetch.php",
method: "POST",
data: {
query: q
},
dataType: "json",
success: function(data) {
$('#total_records').text(data.length);
var row;
if (data.length > 0) {
$.each(data, function(k, d) {
row = $("<tr>");
$("<td>").html(d.title).appendTo(row);
$("<td>").html(d.book).appendTo(row);
$("<td>").html(d.description).appendTo(row);
var e = $("<td>").appendTo(row);
$("<button>").html("VIEW").click(function(e) {
window.location.href = d.url;
}).appendTo(e);
});
} else {
row = $("<tr>");
$("<td>", {
colspan: 4
}).html("No Results Found.").appendTo(row);
}
}
});
}
$('#search').click(function() {
var query = $('#search_id').val();
load_data(query);
});
});
As you can see, this makes use of a few more jQuery parts to help slimline your code. Additionally, we create a Click event callback when the button is created and added to the table.
You had a lot of improper HTML Syntax. My example does not replicate that. A Row Element should contain Cells and not other elements. Yes, you can do it, yet it's not good practice. This is why I removed them. If they are needed for some reason, you should provide a more complete example so it's clear why they are needed.

Change a tooltip content on hover over session times button

My ASP.Net webpage generates buttons with below codes
<a id="1173766" val="248506" titletext="<b>Click to book online for ABC Cinemas</b><strong>$10 tickets </strong>: Preview Screening<br /><br />Seats Available: 35<br />Screening in Cinema 1" target="_self" href="https://localhost:6969/VenueTicketing/Start.aspx?sessionId=248506&cinemaId=cbcc0921bb8e233ab9626690" class="tooltip" title="<b>Click to book online for ABC Cinemas</b><strong>$10 tickets </strong>: Preview Screening<br /><br />Seats Available: 35<br />Screening in Cinema 1">11:30am</a>
When I hover over session I see basic information about session like screen name and seats remaining. Please see screenshot attached
On hover over session I want to display real time seats remaining number, So i am making an ajax call to a function which send api request and get live seats remaining number.
I am trying to update seats remaining number on rendered page by using following java script code.
<script type="text/javascript">
$(document).ready(function () {
function handler(ev) {
var target = $(ev.target);
var sessionid = target.attr('id');
var sessionPOSid = target.attr('val');
var TooolTipText = target.attr('titletext');
target.attr('title', TooolTipText);
if (sessionPOSid == "done")
{
}
else
{
if (target.is(".tooltip")) {
$.ajax({
type: "POST",
url: '../WebService/Home_SessionTimes.asmx/GetSeatsRemaining',
data: "{sessionId: '" + sessionid + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//alert(msg.d);
var n = TooolTipText.indexOf("Seats Available: ");
var t = TooolTipText.substr(n + 17, 3);
if (t.indexOf("<") >= 0) {
if (t.indexOf("<") == 2) {
t = t.replace("<", "");
}
else {
t = t.Substring(0, 1);
}
}
TooolTipText = TooolTipText.replace(t, msg.d);
$('#' + sessionid).attr('title', TooolTipText);
$('#' + sessionid).attr('titletext', TooolTipText);
//$('#' + sessionid).attr('val', "done");
target.attr('title', TooolTipText);
target.tooltiptext = TooolTipText;
},
});
}
}
}
$(".tooltip").mouseover(handler);
});
Above code updates the "titletext" field of tag but does't change anything on "title" field.
Any help would be appreciated.
I have solved this by using qtip. Every time user hovers over div with 'sessiontimes' class, I make ajax call to generate tooltip text (that comes from server based upon session time).
This is my output now:
This is the jQuery code. you need to import qtip css and script files from their website.
<script type="text/javascript">
$(document).ready(function () {
$('.sessiontimes').qtip({
style: { classes: 'qtip-bootstrap' },
content: {
text: function (event, api) {
$.ajax({
url: '../SessionToolTip.aspx',
data: 'sid=' + $(this).children("a").attr("id"),
dataType: "text",
})
.then(function (content) {
api.set('content.text', content);
}, function (xhr, status, error) {
api.set('content.text', status + ':' + error);
});
return 'Loading...';
}
}
});
});
</script>
If you may look at this post and see if the same answer could apply to your situation
JQUERY Change Title not working with tooltip

Cannot display XML in my JavaScript dropdown menu. Why is this not working?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "XML/Website.xml",
dataType: "xml",
success: function (xml) {
var arr = new Array();
$(xml).find("board").each(function () {
var option = $(this).find('brand').text();
if ($.inArray(option, arr) > -1) {
// Do nothing
}
else {
$('#dropdown').append('<option>' + option + '</option>');
arr.push(option);
}
});
}
});
});
</script>
<form>
<select id="dropdown">
<option></option>
</select>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "XML/Website.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('board').each(function () {
var image = $(this).find('image').text();
var name = $(this).find('name').text();
var brand = $(this).find('size').text();
var brand = $(this).find('camber').text();
var price = $(this).find('price').text();
$('#table').append('<tr><td><img width="250px" src="' + image + '"/></td><td>' + name + '</td><td>' + brand + '</td><td>' + price + '</td></tr>');
});
}
});
});
</script>
<table id="table" border="1" cellspacing="5" cellpadding="20" class="center">
<tr><td></td><th>Name</th><th>Camber</th><th>Price</th><th>Size</th></tr>
</table>
</body>
</html>
My XML data is being displayed on the page, but when I use the drop down to select what specifics I want to be selected, It will not change anything. I do not know what I am doing wrong.
My XML tags are all correct I have made sure of it.
In the code you have posted, I don't see where you ask it to change anything when you select something in the drop down.What do you expect it to do? You will need to add a change listener to the drop down, and tell it what to do when it is changed, like this...
$("#dropdown").change(function() {
//Do what you want to do when the drop down is changed.
//You can get the text of the drop down like this...
var selected = $("#dropdown option:selected").text();
});
Also, as a side note, try refactoring your code so you only make the ajax call once, and use the output for both. Looks like your calling the same service twice for the same data which is extra work for no reason.

Make a <td> rendered by Javascript clickable

I'm quite new to webdevelopment and AJAX and I'm facing a little issue there. Basically, I have a form on my webpage. When I submit this form, it makes an AJAX call to my controller, send me the data I want back, and change the html content of the page.
JS code :
$(document).ready(function() {
$("#mydiv table tbody td").click(function() {
alert("You clicked my <td>!" + $(this).html() +
"My TR is:" + $(this).parent("tr").html());
});
$('#myform').submit(function()
{
try {
var host = $("#host").val();
var port = $("#port").val();
var username = $("#username").val();
var password = $("#password").val();
var database = $("#database").val();
$.ajax({
type: "POST",
url: "/management/connectDatabase",
dataType: "JSON",
data: "host="+host+"&port="+port+"&username="+username+"&password="+password+"&database="+database,
cache: false,
success:
function(data){
$('#mydiv').html(show_tables(data));
},
});
return false;
}
catch(e){
console.debug(e);
}
});
});
function show_tables(data)
{
var html = '<div id="mydiv">';
html += '<table class="display" id="example">';
html += '<thead><tr><th>Tables</th></tr></thead><tbody>';
for (var tablesCount = 0; tablesCount < data.tables.length; tablesCount++){
html += '<tr class=gradeA id="trtest">';
html += '<td id="tdtest">' + data.tables[tablesCount] + '</td>';
html += '</tr>';
}
html += '</tbody></table>';
html += '</div>';
return html;
}
When I submit the form, the HTML is generating right, and I can see my content. But, I can't click on any entries of the <table>. Moreover, when I want to see the sourcecode of my page, it doesn't displays me the table, but still my form, even if it has still been validated.
Could someone explain me what I do wrong here ?
Depending on which jQuery version you're using, you need to either bind the click event using jQuery.delegate or jQuery.on in order for things to work with dynamically added DOM elements.
Edit: as pointed out by Geert Jaminon, you have to use the selector parameter of the on function. This works for me.
$("#mydiv table tbody").on('click', 'td', function() {
alert("You clicked my <td>!" + $(this).html() +
"My TR is:" + $(this).parent("tr").html());
});
$("#mydiv table tbody").on('click', 'td', function() {
alert("You clicked my <td>!" + $(this).html() + "My TR is:" + $(this).parent("tr").html());
});
.live() is replaced by .on() in the newer jQuery versions.
http://jsfiddle.net/ZqYgv/
you need to bind the click event handler after the rendering of the elements, since they weren't in place when you made the binding.
If you insert data dynamically, you need to add the click event after the data has been inserted.
http://codepen.io/thomassnielsen/pen/FEKDg
$.post('ajax/test.html', function(data) {
$('.result').html(data);
// Add .click code here
});

Categories