I am trying to program something that reads in file data, stores specific information in an array, then exports that array to a different javascript file. In the javascript file, in which I import the array, I am trying to create a button that has text-based off of the array.
The problem I am having is that after I import the array and initialize the button, it will not appear. However, if I don't import anything and have the same code to initialize my button (but with me writing random stuff for the button's text), it works fine. Also, I am sure that the array is being exported/imported fine because if I use console.log(names[0]) in the file I export it to, it will output the correct value. To clarify, if I include the import statement, I do not get an error, but the button just will not appear on the Chrome tab that it should appear on.
My first javascript file (why.js):
import fs from 'fs';
let names = [];
var lines = fs.readFileSync('input.txt').toString().split("\n");
for(let line = 0; line < lines.length; line++){
let word = "";
let info = 0;
for(let ind = 0; ind < lines[line].length; ind++){
word += (lines[line]).charAt(ind);
if((lines[line]).charCodeAt(ind) < 32 || (lines[line]).charCodeAt(ind) > 122){
info++;
if(info == 1){
names.push(word);
}
word = "";
}
}
}
export { names };
my second javascript file (buttons.js):
//if I don't include this line, the button will initialize and appear
import { names } from './why.js'
let button = document.createElement('button');
button.innerHTML = 'artichoke';
//i want it to be: button.innerHTML = names[0];
document.body.appendChild(button);
console.log(names[0]);
I'm not sure if this is important, but here is my html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>something random here for now ig</h1>
<script src="why.js"></script>
<script src="buttons.js"></script>
</body>
</html>
TLDR: After I import an array from my first javascript file to another, I am unable to create any button at all (though the code runs without error), but if I don't import anything, the button is created fine and appears.
Thank you for reading, and I would appreciate any feedback or tips :)
Aim:
The background loop will continuously read and print the file (word.txt)
Pressing one of the buttons will overwrite the value in word.txt
This change will then be read by the background loop and printed
What happens:
The background loop continuously reads and prints the file (word.txt)
Pressing one of the buttons overwrites the value in word.txt
but.... 3. This change isn't reflected in JS until I go on to the "word.txt" file in a different browser and refresh the page. Once this is done, JS starts recognizing it.
Any ideas? Sorry the snippet doesn't work as it has php in
var instanse = false;
var state;
var mes;
var file;
console.log('update.js loaded');
function triggerUpdate(){
console.log('update.js is triggered');
updateChat();
}
//Background Loop
function updateChat(){
var file = 'word.txt';
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
console.log(allText);
}
}
}
rawFile.send(null);
setTimeout(updateChat, 1500);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Random Word Generator</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script language="javascript" src="update.js" type="text/javascript"></script>
</head>
<body onload="triggerUpdate();">
<form action="" method="post">
<input type="submit" name="word"
class="button" value="Button1" id="button1"/>
<input type="submit" name="word"
class="button" value="Button2" id="button2"/>
</form>
<?php
//This function gets called when button is pushed
function postword(){
$fp = fopen('word.txt', 'w');
fwrite($fp, $_POST['word']);
fclose($fp);
}
//When the button is pushed, the function will be called
if (isset($_POST['word'])) {
postword();
return;
}
?>
</body>
</html>
The browser is caching the initial result of the XMLHttpRequest call. The easiest workaround is to fool the cache by appending a random number as a parameter to the url. it will get ignored by the filesystem when looking for the file.
You can add any query variable you want ('v' is popular - sort of stands for version).
There are many ways to get a random number but using the Unix timestamp - Date.now()
- is an easy one that should do the trick in this case.
Change code from:
var file = 'word.txt';
To:
var file = 'word.txt?v=' + Date.now();
This which will create a call to a url like this: word.txt?v=1519211809934
I need my webite to display info in a certain language, based on a query in my webite's URL (e.g. www.website.com/index.php?country=FR). How can I do that with vanilla JS and not React/Angular?
My approach:
1) JS recognizes a query in the URL (in this case- 'country=FR') and then appends a js file, which has neccessary french words in it defined by variables.
2) JS in my script tag that's in the HTML file, appends the main page markup text with template literals in it.
3)
I don't know, whether the browser fails to either fetch the language file itself or its variables. At the moment it does not render anything.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./js/main.js"></script>
</head>
<body>
<script>
const template= `
<h1>Good Morning: ${goodmorning} </h1>
<h2>Good Evening: ${goodevening} </h2>
<h3>My name is: ${mynameis}</h3>`
function markupAppend() {
$('body').html(template);
console.log('Markup loaded')
}
markupAppend()
</script>
</body>
</html>
=========================
Main.js
var domain = window.location.href;
var FRString = domain.includes("country=FR");
var ESString = domain.includes("country=ES");
if (FRString) {
$('head').append(`<script src="./Language_files/FRENCHwords.js" />`)
}
if (ESString) {
$('head').append(`<script src="./Language_files/SPANISHwords.js" />`)
}
=========================
FRENCHwords.js
const goodmorning = 'Bonjour';
const goodevening = 'Bonsoir';
const mynameis = 'Mon nom est';
=========================
SPANISHwords.js
const goodmorning = 'Buenos dias';
const goodevening = 'Buenas tardes';
const mynameis = 'Mi nombre es';
No errors displayed, the page is just not rendering...
In Your main.js file, you are using domain.includes, it only returns the domain name but not the entire URL. You can use window.location.href.includes for this.
Instead of: domain.includes("country=FR");
Try: window.location.href.includes("country=FR");
I have a little project going to log temperatures and such to a MySQL database, and I'd like to provide for accessing that info from anywhere.
My initial crude attempt worked pretty well (simply a PHP file getting the MySQL data into an HTML table)
Now I'd like to use some pretty graphs in this project and I've failed despite many many many hours of googling.
Here's the PHP and js/HTML files.
(edit: removed all the mysql stuff to focus on the php->js connection)
this is the php file.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<?php
$phpvar = ( {labels: ['One', 'Two', 'Three'], series: [[8, 13, 21]] });
$jsvar = json_encode($phpvar);
?>
</body>
</html>
Next, the js/HTML page where I'm trying to pull the data from the PHP script in so that it can be displayed using chartist...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<! include chartist>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<! include ajax jquery >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</head>
<body>
<div class="ct-chart ct-double-octave" id="chart1"></div>
<div id="testdiv">
</div>
<script type="text/javascript">
$.getJSON('stackphp.php', function(data) {
var jsvar = JSON.parse(data);
console.log(jsvar);
var sample= {
labels: ['One', 'Two', 'Three'],
series: [
[8, 13, 21],
[1, 2, 3]
]
}
var chart = new Chartist.Bar('.ct-chart', sample);
</script>
</body>
</html>
#T.Shah... Interestingly, this code does display a sample graph sucessfully...IF if remove the three lines 1 $.getJSON('stackphp.php', function(data) {
var jsvar = JSON.parse(data);
console.log(jsvar);`
Leaveing those three line in however, breaks the whole page... even thought the jsvar variable isn't used in the chartist function. Not sure why that is.
This project is making it clear to me how little I've actually dabbled in web code before. If I can get a fingertip's worth of grip on what I'm missing, I'll pound away at this as much as needed.
Many thanks.
so this project has taught me just tons about javasript, php, and the rest of the webstack.
I’ll try to outline the answer to my original question in case someone else finds this via google.
First, getting data out of mysql using php was pretty easy. Here’s that code…
Setting up a convenient set of variables…
<?php
$hostname = "localhost";
$username = “mysqladminusername”;
$password = “mysqladminpass”;
$db = “tablename”;
$dbconnect=mysqli_connect($hostname,$username,$password,$db);
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
?>
then pulling the data….
<?php
set_time_limit (60); //needed to prevent timeout error mysql reports the unlimited script takes ~30sec
$query = mysqli_query($dbconnect, "SELECT * FROM tablename ORDER by idcolumnname DESC limit 2000")
or die (mysqli_error($dbconnect));
?>
Then reading the data and putting into an html table…. and creating php arrays with the contents of each mysql column.
<?php
while ($row = mysqli_fetch_assoc($query)) {
echo
"<tr>
<td>{$row[‘col1name’]}</td>
<td>{$row[‘col2name’]}</td>
<td>{$row['col3name’]}</td>
<td>{$row[‘col4name’]}</td>
</tr>\n";
$phpcol1[] = $row[‘col1name’];
$phpcol2[] = $row[‘col2name’];
$phpcol3[] = $row[‘col3name’];
$phpcol4[] = $row[‘col4name’];
}
?>
At this point the php arrays are formatted as normal php “associative arrays”… something like this….
array(10) { [0]=> array(1) { [“col1name”]=> string(3) "658" } [1]=> array(1) { [“col1name”]=> string(3) "657" } [2]=> array(1) { [“col1name”]=> string(3) "658" }
….which is not very useful since chartist doesn’t understand it.
So we need to convert it to the format chartist expects, e.g. [232,345,4545,343,235,32]
(keep in mind that this array is one of two that chartist requires, it needs an array of “labels” and an array of “series”… and then the chartist demo code puts those together and uses them in the final bit of code that actually creates the chartist graph.)
We do this conversion using json encoding.
This can be done in stages, using variables to separate the code for readability, or as a oneliner for compactness.
The compact version is the method I chose in the end.
e.g….
<script type=“text/javascript”>
var jsonlabelsdatavariable = <?php echo json_encode($phpcol1) ?>;
var jsonseriesdatavariable = <?php echo json_encode($phpcol2) ?>;
//comment…here I found it useful to print the formatted array data to the screen so I could see the change with my eyes. To do this, I created an html dviv element like this….
<div class="container" id=“showmethedata”></div>….
in the body of the html page then I put the array data in with the following code…
document.getElementById(“showmethedata”).innerHTML
//comment… while I was testing this, I used placeholder data in the chartist demo code so that I could switch back and forth between the working demo code, and the broken custom code, and use developer tools to see the problems. so below you’ll see that the chartist demo code starts out filled with my placeholder data, then gets emptied out, and then overwritten with the real data from the json variable.
//This is the chartist demo code…..(notice the line feed, I was testing for characters that would break the chartist display, since a problem I had at that time was all the label data being shown in one point of the graph. Turns out this problem was not from bad characters, but that I was pushing my label data into a single label array element.
var data = {
labels: ['2222-02-13_09:12:00','2018-02-13_09:11:00','2018-02-13_09:10:00','2018-02-
13_09:09:00','2018-02-13_09:08:00'],
series: [
[5,2,4,2,0]
]
};
//Now I blank the placeholder arrays…
data.labels.length = 0;
data.series.length = 0;
//now I fill the arrays with the real data…note that two methods are used. this is due to the formatting that chartist expects… the labels array is a single array with elements… while the series array contains an inner array, and that inner array contains the elements. using the push method on the labels array resulted in the labels array being shows as a label for a single data point on the graph.
data.labels = data.labels.concat(jsonlabelsdatavariable);
data.series.push(jsonlight);
//finally we can build the chartist graph…
new Chartist.Line('.ct-chart', data, { width:10000, showArea:true, reverseData: true, });
//and lastly, we close the javascript tag.
</script>
I’ll also note i woulnd up using a few custom functions that edited the contents of my php array elements to do things like remove spaces, add or remove quote marks around each element, etc… but i don’t think any of that was actually necessary.
e.g.
function addquotes ($element){
return "'{$element}'";
}
$withquotes = array_map("addquotes", $sourcearray);
function killspace ($anothersourcearray){
return str_replace(' ' , '_', $anothersourcearray);
}
$phpkillspace = array_map("killspace", $anothersourcearray);
$unspecial = preg_replace("/[^a-zA-Z 0-9]+/", "", $finalsourcearray );
What an adventure.
Cheers!
I was flowing #David 's code and had problems in few spots, so for reference, here is my complete code:
<?php
//here is connection information
require "cont.php";
$db = db_connect();
$upit = "SELECT * FROM (
SELECT * FROM meteo LIMIT 1000
) sub
ORDER BY id ASC";
$rezultat = mysqli_query ($db, $upit);
db_disconnect($db);
$label = array();
$series = array();
if ($rezultat != null)
{
$i = 0;
$j = 0; //vairable for sciping few database enteries.
while($red = mysqli_fetch_assoc($rezultat))
{
$j++;
if ($j == 1)
{
$t = date_create($red['at']);
$label[$i] = date_format($t, 'H:i');
$series[$i] = array($red['dht_temp'], $red['bmx_temp']);
//$series[$i] = array($red['id'], $red['dht_temp'], $red['bmx_temp'], $red['hum'], $red['press'], $red['w_speed'], WindDirectionToString($red['w_dir']));
$i++;
}
// how meny entries to scip
if($j == 10) {
$j = 0;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
</head>
<body>
<div class="ct-chart ct-perfect-fourth"></div>
<script type="text/javascript">
var data = {
labels: <?php echo json_encode($label) ?>,
series: <?php echo json_encode($series); ?>
};
var options = {
width: 1000,
height: 500
};
new Chartist.Line('.ct-chart', data, options);
</script>
</body>
</html>
You need to make sure that '100.php' file return data in the format that chartist expects. If you can make sure of that, then your html file could be like this. Then remove the random data part.
<!DOCTYPE html>
<html>
<head>
<! include chartist>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<! include ajax jquery >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</head>
<body>
<div class="ct-chart ct-double-octave" id="chart1"></div>
<div id="testdiv">
</div>
<script type="text/javascript">
$.getJSON('100.php', function(data) {
var jsvar = JSON.parse(data);
console.log(jsvar);
// jsvar = {
// // random test data just to build a visible chart
// labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
// // random test data just to build a visible chart
// series: [
// [5, 2, 4, 2, 0]
// ]
// };
// Create a new line chart object where as first parameter we pass in a selector
// that is resolving to our chart container element. The Second parameter
// is the actual data object.
new Chartist.Bar('.ct-chart', jsvar);
});
</script>
</body>
</html>
I'm trying to get the html of www.soccerway.com. In particular this:
that have the label-wrapper class I also tried with: select.nav-select but I can't get any content. What I did is:
1) Created a php filed called grabber.php, this file have this code:
<?php echo file_get_contents($_GET['url']); ?>
2) Created a index.html file with this content:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>test</title>
</head>
<body>
<div id="response"></div>
</body>
<script>
$(function(){
var contentURI= 'http://soccerway.com';
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
});
var LI = document.querySelectorAll(".list li");
var result = {};
for(var i=0; i<LI.length; i++){
var el = LI[i];
var elData = el.dataset.value;
if(elData) result[el.innerHTML] = elData; // Only if element has data-value attr
}
console.log( result );
</script>
</html>
in the div there is no content grabbed, I tested my js code for get all the link and working but I've inserted the html page manually.
I see a couple issues here.
var contentURI= 'http:/soccerway.com #label-wrapper';
You're missing the second slash in http://, and you're passing a URL with a space and an ID to file_get_contents. You'll want this instead:
var contentURI = 'http://soccerway.com/';
and then you'll need to parse out the item you're interested in from the resulting HTML.
The #label-wrapper needs to be in the jQuery load() call, not the file_get_contents, and the contentURI variable needs to be properly escaped with encodeURIComponent:
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
Your code also contains a massive vulnerability that's potentially very dangerous, as it allows anyone to access grabber.php with a url value that's a file location on your server. This could compromise your database password or other sensitive data on the server.