I have a list of airport codes, names, and locations in an Excel Spreadsheet like the below:
+-------+----------------------------------------+-------------------+
| Code | Airport Name | Location |
+-------+----------------------------------------+-------------------+
| AUA | Queen Beatrix International Airport | Oranjestad, Aruba|
+-------+----------------------------------------+-------------------+
My Javascript is passed a 3 character string that should be an airline code. When that happens I need to find the code on the spreadsheet and return the Airport Name and Location.
Im thinking something like:
var code = "AUA";
console.log(getAirportInfo(code));
function getAirportInfo(code) {
// get information from spreadsheet
//format info (no help needed there)
return airportInfo;
}
Where the log would write out:
Oranjestad, Aruba (AUA): Queen Beatrix International Airport
What is the easiest method to get the data I need from the spreadsheet?
Extra Info:
The spreadsheet has over 17,000 entries
The function alluded to above may be called up to 8 times in row
I don't have to use an Excel Spreadsheet thats just what I have now
I will never need to edit the spreadsheet with my code
I did search around the web but everything I could find was much more complicated than what Im trying to do so it made it hard to understand what Im looking for.
Thank you for any help pointing me in the right direction.
I ended up using a tool at shancarter.com/data_converter to convert my flie to a JSON file and linked that to my page. Now I just loop through that JSON object to get what I need. This seemed like the simplest way for my particular needs.
I've used a plain text file(csv, or tsv both of which can be exported directly from Excel)
Loaded that into a string var via xmlhttprequest. Usually the browsers cache will stop having to download the file on each page load.
Then have a Regex parse out the values as needed.
All without using any third party....I can dig the code out if you wish.
Example:
you will need to have the data.txt file in the same web folder as this page, or update the paths...
<html>
<head>
<script>
var fileName = "data.txt";
var data = "";
req = new XMLHttpRequest();
req.open("GET", fileName, false);
req.addEventListener("readystatechange", function (e) {
data = req.responseText ;
});
req.send();
function getInfoByCode(c){
if( data == "" ){
return 'DataNotReady' ;
} else {
var rx = new RegExp( "^(" + c + ")\\s+\\|\\s+(.+)\\s+\\|\\s+\\s+(.+)\\|", 'm' ) ;
var values = data.match(rx,'m');
return { airport:values[2] , city:values[3] };
}
}
function clickButton(){
var e = document.getElementById("code");
var ret = getInfoByCode(e.value);
var res = document.getElementById("res");
res.innerText = "Airport:" + ret.airport + " in " + ret.city;
}
</script>
</head>
<body>
<input id="code" value="AUA">
<button onclick="clickButton();">Find</button>
<div id="res">
</div>
</body>
</html>
Related
Overview:
I am creating a web page using Python and generating both html as well as javascript in my code. Additionally, I am parsing through csv files and converting their table data to html. I want to be able to click on a line of text and the associated table data for that text would then be loaded into an iframe on the currently active web page. The problem I am having, is that my javascript function is not recognizing the key I send it to retrieve the corresponding table data. If I manually enter the key to return the table data, the correct data is returned - though the table doesn't load. However, if I generate the key programmatically, it returns as 'undefined' even though the strings appear to be identical.
Goal:
I need to figure out if there is something wrong with either the syntax, or the format of the key I am using to try and retrieve the table data. Secondly, I need to figure out why the table data is not being correctly loaded into my iframe.
Example:
import pandas
opening_html = """<!DOCTYPE html><h1> Test</h1><div style="float:left">"""
table_html = pandas.DataFrame({'Col_1':['this', 'is', 'a', 'test']}).to_html()
tables_dict = {'test-1 00': table_html}
java_variables = "%s" % json.dumps(tables_dict)
table_frame = """<iframe name="table_frame" style="position:fixed; top:100px; width:750; height:450"></iframe>"""
test_link_text = """ test-1<br>"""
java = """<script type='text/javascript'>
var table_filename = """ + java_variables + ";"
java += """function send_table_data(obj) {
var t = obj.text + ' 00';
alert(t)
//This line below will not work
var table_data = table_filename[t];
//But this line will return the correct value
var table_data = table_filename['test-1 00'];
alert(table_data);
//This line should load the data, but does nothing
document.getElementsByName('table_frame').src = table_data;
}
</script>"""
html_text = """<head>
<link rel="stylesheet" href="style.css">
</head>""" + test_link_text + table_frame + """<body>""" + "</div>" + java + '</body>'
with open('test_table_load.html', 'w') as w:
w.write(html_text)
EDIT: I did just figure out that for some reason there was a default space at the beginning of the var t - so using trim() seemed to fix that. Now, the only issue left is why the data doesn't load into the table.
It looks like you figured out your typo with the space that was messing with your key, so this is for your second question.
Your code
So to get your table to populate in the iframe you need to fix three things:
To edit the HTML contents of your iframe you should be setting the .srcdoc element, not .src
The document.getElementsByName() function will return an array of HTML elements so in order to get the element you want you should do one of the following:
(recommended) switch to using document.getElementById and use id='table_frame' in your iframe tags
select the first element of the array by using document.getElementsByName('table_frame')[0]
The anchor tag that you're using as the trigger for your function is redirecting you back to the original HTML page, stopping you from seeing any of the changes your javascript function is making. A simple solution to this is to switch to using a <button> element in place of <a>.
Here is what your code looks like with the fixes:
import pandas
import json
opening_html = """<!DOCTYPE html><h1>Test</h1><div style="float:left">"""
table_html = pandas.DataFrame({'Col_1':['this', 'is', 'a', 'test']}).to_html()
tables_dict = {'test-1 00': table_html}
java_variables = "%s" % json.dumps(tables_dict)
table_frame = """<iframe id="table_frame" style="position:fixed; top:100px; width:750; height:450"></iframe>"""
test_link_text = """<button href='' onclick="send_table_data(this);"> test-1</button><br>"""
java = """<script type='text/javascript'>
var table_filename = """ + java_variables + ";"
#for the button, innerText needs to be used to get the button text
java += """function send_table_data(obj) {
var t = obj.innerText + ' 00';
alert(t)
//This line below will not work
var table_data = table_filename[t];
//But this line will return the correct value
var table_data = table_filename['test-1 00'];
alert(table_data);
//This line should load the data, but does nothing
document.getElementById('table_frame').srcdoc = table_data;
}
</script>"""
html_text = """<head>
<link rel="stylesheet" href="style.css">
</head>""" + test_link_text + table_frame + """<body>""" + "</div>" + java + '</body>'
with open('test_table_load.html', 'w') as w:
w.write(html_text)
Other Recommendations
I strongly suggest looking into some python frameworks that can assist you in generating your website, either using HTML templates like Flask, or a library that can assist in generating HTML using Python. (I would recommend Dash for your current use case)
Attempting to create a script that will pull information from an API requested XML document and put it into a 2D array.
Upon making the Get request
https://api.example.com/v1.svc/users?apikey=MY-KEY&source=MY-APP&limit=1000
An XML is produced for each user looking like
<User>
<Id>Rdh9Rsi3k4U1</Id>
<UserName>firstlast#email.com</UserName>
<FirstName>First</FirstName>
<LastName>Last</LastName>
<Active>true</Active>
<Email>firstlast#email.com</Email>
<AccessLevel>Learner</AccessLevel>
</User>
Each user has a similar looking output stacked on top of each other. How could this be scrubbed into an array? Example, the first array would have 7 "columns" with all shown information with each user having a row.
b
So I figured it out for anyone looking for an answer to this type of question in the future. Basically, I found out that the API I was trying to reach (not actually "citrowske.com" as shown in the example) did not allow for CORS or jsonp which left me with the only option of using a Proxy.
Shown is an example of code similar to what I ended up using (below), along with the test XML file shown here
A basic explanation of how this works, it uses the proxy to get the XML file and stores it as "xml" found as "function(xml)". Then the XML doc is searched and each section that starts with "User" gets the "FirstName" and "LastName" data pulled from it and appended to dropdown in the HTML section named "yourdropdownbox".
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'http://citrowske.com/xml.xml',
function (xml) {
//console.log("> ", xml);
//$("#viewer").html(xml);
////////////////////////////////////
var select = $('#yourdropdownbox');
select.append('<option value="">Select a User</option>');
$(xml).find('User').each(function(){
var FirstNames = $(this).find('FirstName').text();
var LastNames = $(this).find('LastName').text();
select.append("<option value='"+ FirstNames +"'>"+FirstNames+" "+LastNames+"</option>");
});
}
////////////////////////////////////
);
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select id="yourdropdownbox">
</select>
As a note, Proxy's are not known for being extremely secure, so watch out what you use this for.
Also, if I wanted to turn the data into an array instead of appending it each time I could have added
var firstnamesarray = ["0"];
var lastnamesarry = ["0"];
var i = 0;
Above the top row of forward-slashes and then replaced:
var FirstNames = $(this).find('FirstName').text();
var LastNames = $(this).find('LastName').text();
with
firstnamesarry[i] = $(this).find('FirstName').text();
lastnamesarry[i] = $(this).find('LastName').text();
i = i+1;
and replaced the "select.append" First & Last Names with
firstnamearry[i] & lastnamearry[i]
To view a working example, check out the jsfiddle here
Context : I'm working on a site that runs on my university's server (IIS, not Apache), no way to use PHP.
I want the site to be so simple that people with very little HTML/CSS/js knowledge can put new content when I'll be done with it. I'm a grad student in health sciences and I've learned HTML, CSS, etc. by myself since a few years (so I'm definitely not a pro), so pardon me if my question is a little naive.
I'd really need some script/tool that would allow me to :
Get content from an external file (blog post) on the server (let's say a list of ".html" files located in a folder on the server, let's say the folder "/blog-posts/", containing a bunch of files named "jan-15.html", "feb-15.html", etc.)
Pick the last 4 files (4 most recent)
Insert this content at a precise point in a html file
(Optional, but it would really be nice) Pull the date the file was last edited, put it in a string and insert said string before the blog post, in the home page
So :
Do anyone know if anything like this already exists ?
If not, do you guys think it's possible with some js/jQuery to "manipulate" external files like that ?
If it's possible, any hints how :) ?
Thanks a million times, I know I'm asking a lot, but I've been searching for a viable solution for this for the last few months... It's my first time writing here but I've been an avid reader since a very long time.
Have a great day !
You can store a simple blog configuration as a JSON object and update it as you add new posts. Let's say you have the files jan.html and feb.html in your blog-posts folder.
Now in the main folder, create a file content.json as follows this:
{
"posts": [
{ "uri": "feb.html", "date": "2/12/15" },
{ "uri": "jan.html", "date": "1/3/15" }
]
}
Now you can get the blog content with AJAX requests from JavaScript. Example:
<script>
function Init(posts)
{
var e = document.getElementById('content');
var s = '';
posts.forEach(function(post)
{
console.log(post.content);
s += '<div><h2>Date: ' + post.date + '</h2><p>' + post.content + '</p></div>';
});
e.innerHTML = s;
}
function LoadContent(config)
{
var remain = config.posts.length;
var posts = [];
config.posts.forEach(function(post)
{
var req = new XMLHttpRequest();
req.open('GET', 'blog-posts/' + post.uri, true);
req.onload = function()
{
remain--;
posts.push({ content: req.responseText, date: post.date });
if(remain === 0)
{
Init(posts);
}
};
req.send(null);
});
}
function LoadConfig()
{
var req = new XMLHttpRequest();
req.open('GET', 'content.json', true);
req.onload = function()
{
LoadContent(JSON.parse(req.responseText));
};
req.send(null);
}
window.addEventListener('load', LoadConfig);
</script>
<div id="content"></div>
I’m making a random sentence generator for my English class. I’m close but because of my limited php and javascript knowledge I need to ask for help. I’m not bad at reading the code, I just get stuck writing it.
I want to use explode to break up a string of comma seperated values. The string is a mix of English and Spanish, on the .txt file they would seperated like:
The book, El libro
The man, El hombre
The woman, La mujer
etc.
I would like to break these two values into an array and display them in separate places on my web page.
I`m going to use a random text generator script that I found, it’s working great with no problems. I just need to modify it using explode to read, separate the values into an array, and be able to display the separate values of the array.
<?php
/* File, where the random text/quotes are stored one per line */
$settings['text_from_file'] = 'quotes.txt';
/*
How to display the text?
0 = raw mode: print the text as it is, when using RanTex as an include
1 = Javascript mode: when using Javascript to display the quote
*/
$settings['display_type'] = 1;
/* Allow on-the-fly settings override? 0 = NO, 1 = YES */
$settings['allow_otf'] = 1;
// Override type?
if ($settings['allow_otf'] && isset($_GET['type']))
{
$type = intval($_GET['type']);
}
else
{
$type = $settings['display_type'];
}
// Get a list of all text options
if ($settings['text_from_file'])
{
$settings['quotes'] = file($settings['text_from_file']);
}
// If we have any text choose a random one, otherwise show 'No text to choose from'
if (count($settings['quotes']))
{
$txt = $settings['quotes'][array_rand($settings['quotes'])];
}
else
{
$txt = 'No text to choose from';
}
// Output the image according to the selected type
if ($type)
{
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
// Set the correct MIME type
header("Content-type: text/javascript");
// Print the Javascript code
echo 'document.write(\''.addslashes($txt).'\')';
}
else
{
echo $txt;
}
?>
The script that displays the result:
<script type="text/javascript" src="rantex.php?type=1"></script>
Can someone please help me modify the rantex.php file so that I can use explode to separate the different comma separated values, and use a different script to call them in different places on my web page?
Thank you, and please excuse my noobness.
The following seems unnecessary, since file() will have already removed new line characters:
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
To break your line, you may instead use:
list($english, $spanish) = explode(', ', trim($txt));
It seems you are trying to use PHP to serve a static page with some random sentences, right? So why not use PHP to serve valid JSON, and handle to display logic on the client?
Heres a quick implementation.
// Get the data from the text file
$source = file_get_contents('./quotes.txt', true);
// Build an array (break on every line break)
$sentences = explode("\n", $source);
// Filter out empty values (if there is any)
$filtered = array_filter($sentences, function($item) {
return $item !== "";
});
// Build a hashmap of the array
$pairs = array_map(function($item) {
return ['sentence' => $item];
}, $filtered);
// Encode the hashmap to JSON, and return this to the client.
$json = json_encode($pairs);
Now you can let the client handle the rest, with some basic JavaScript.
// Return a random sentence from your list.
var random = sentences[Math.floor(Math.random() * sentences.length)];
// Finally display it
random.sentence
[edit]
You can get the JSON data to client in many ways, but if you don't want to use something like Ajax, you could simply just dump the contents on your webpage, then use JavaScript to update the random sentence, from the global window object.
// Inside your php page
<p>English: <span id="english"></span></p>
<p>Spanish: <span id="spanish"></span></p>
<script>
var sentences = <?= json_encode($pairs); ?>;
var random = sentences[Math.floor(Math.random() * sentences.length)];
var elspa = document.getElementById('spanish');
var eleng = document.getElementById('english');
elspa.innerText = random.sentence.split(',')[1];
eleng.innerText = random.sentence.split(',')[0];
</script>
Ok, so I have this figured out, I take 0 credit because I paid someone to do it. Special thanks to #stormpat for sending me in the right direction, if not for him I wouldn't have looked at this from a JSON point of view.
The .PHP file is like so:
<?php
$f_contents = file('quotes.txt');
$line = trim($f_contents[rand(0, count($f_contents) - 1)]);
$data = explode(',', $line);
$data['eng'] = $data[0];
$data['esp'] = $data[1];
echo json_encode($data);
?>
On the .HTML page in the header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
(function ($) {
$(function()
{
function load_random_data() {
$.get('random_line.php', function(data) {
var data = $.parseJSON(data);
$('#random_english').text(data.eng);
$('#random_spanish').text(data.esp);
});
}
load_random_data();
$('#get_random').click(function(e){
e.preventDefault();
load_random_data();
});
});
})(jQuery);
</script>
This splits the different variables into classes, so to call them into my html page I call them by their class, for instance I wanted to drop the variable into a table cell so I gave the individual td cell a class:
<td id="random_spanish"></td>
<td id="random_english"></td>
Plus as a bonus the coder threw in a nifty button to refresh the json classes:
<input type="button" value="Get random" id="get_random" />
So now I don`t have to have my students refresh the whole web page, they can just hit the button and refresh the random variables.
Thanks again everyone!
this is my first time here as a poster, please be gentle! I have zero knowledge of JS (yet, working on it) but am required to do some JS anyway. Here's my problem. I got some code (not mine) allowing a user to select multiple choices. I found the function that gathers these choices and store them
function getProductAttribute()
{
// get product attribute id
product_attribute_id = $('#idCombination').val();
product_id = $('#product_page_product_id').val();
// get every attributes values
request = '';
//create a temporary 'tab_attributes' array containing the choices of the customer
var tab_attributes = [];
$('#attributes select, #attributes input[type=hidden], #attributes input[type=radio]:checked').each(function(){
tab_attributes.push($(this).val());
});
// build new request
for (var i in attributesCombinations)
for (var a in tab_attributes)
if (attributesCombinations[i]['id_attribute'] === tab_attributes[a])
request += '/'+attributesCombinations[i]['group'] + '-' + attributesCombinations[i]['attribute'];
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')// DISPLAY ATTRIBUTES SUMMARY
request = request.replace(request.substring(0, 1), '#/');
url = window.location + '';
// redirection
if (url.indexOf('#') != -1)
url = url.substring(0, url.indexOf('#'));
// set ipa to the customization form
$('#customizationForm').attr('action', $('#customizationForm').attr('action') + request);
window.location = url + request;
}
I need to make a simple display summary of these choices. After quite a bit of searching and findling, I came with the line with the DISPLAY SUMMARY comment, this one:
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')
In the page where I want those options, I added an empty div with the same ID (attsummary):
<div id="attsummary"></div>
Obviously, it is not working. I know I don't know JS, but naively I really thought this would do the trick. May you share with me some pointers as to where I went wrong?
Thank you very much.
Correct form of the line it isn't working for you:
$('#attsummary').html($('#attsummary').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')