In my code i've a file called "orca.txt" it is just a number writen in this.
it looks like:
2300
I use fetch to read this number, i get it with:
fetch('orca.txt')
.then(response => response.text())
.then(textString => { contador=textString; });
It works very well, but then after i need to increase the value from the var contador,
so I use contador++; after i wanna to save this new value into the file "orca.txt"
i've tried this:
contador++;
var ct=contador.toString();
fetch("orca.txt",{method:'POST', body:ct})
.then (response => response.text());
but when i refresh the page or open in server the file orca.txt the value is same.
Can anyone help me how to write a value into a file (server file, no user file) using POST method?
Using PHP and file_put_contents and JS's Fetch API with FormData API
Create an index.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>DEMO</title>
</head>
<body>
<button id="increment" type="button">INCREMENT</button>
<input id="counter" type="text" readonly>
<script>
const EL_increment = document.querySelector("#increment");
const EL_counter = document.querySelector("#counter");
let counter = 0;
const incrementCounter = () => {
counter = parseInt(counter) + 1;
const FD = new FormData();
FD.append("counter", counter);
fetch("saveCounter.php", {
method: 'post',
body: FD
}).then(data => data.json()).then((res) => {
EL_counter.value = res.counter;
});
};
const init = async () => {
EL_increment.addEventListener("click", incrementCounter);
counter = await fetch('counter.txt').then(response => response.text());
EL_counter.value = counter;
};
init();
</script>
</body>
</html>
create counter.txt file:
2300
Create a saveCounter.php file:
<?php
$response = ["status" => "error"];
if (isset($_POST["counter"]) && file_put_contents("counter.txt", $_POST["counter"])) {
$response = ["status" => "success", "counter" => $_POST["counter"]];
}
echo json_encode($response);
exit;
Spin up your localhost server or for a quick test using cli-server run from terminal:
php -S localhost:8081
and head to http://localhost:8081 to try it out
Related
I'm creating a chat application using socket.io, so basically what I'm trying is to console.log the user who joined the chat, here I'm taking a prompt from the client and emitting to the server, but cannot find any log in my command line. And on top I'm getting this error ERR_NAME_NOT_RESOLVED.
ERR_NAME_NOT_RESOLVED img
Index Html:
<!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>See-me</title>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="js/client.js"></script>
<link rel="stylesheet" href="css/styles.css">
<link rel = "icon" href ="logo/appIcon.ico" type = "image/x-icon">
</head>
<body>
</body>
</html>
Client Side Js:
const socket = io('http//localhost:3000')
const form = document.getElementById('send-container')
const messageInput = document.getElementById('messageImp')
const messageContainer = document.querySelector(".container")
const userName = prompt("Enter your Name to join");
socket.emit('new-user-joined', userName)
Server Side JS:
const io = require('socket.io')(3000)
const users = {};
io.on('connection', (socket) => {
socket.on('new-user-joined', userName =>{
console.log("New user", userName);
users[socket.id] = userName;
socket.broadcast.emit('user-joined', userName)
});
socket.on('send', message => {
socket.broadcast.emit('receive', {message: message, userName: users[socket.id]})
});
})
All I want is to console log the user who joined the chat.
The error is actually pointing to what the issue is:
const socket = io('http//localhost:3000')
That URL is missing a colon after http
I am using Firebase to get the data
code:
const admin = require('firebase-admin');
const serviceAccount = require("C:/Users/santo/Downloads/bestmpos-firebase-adminsdk.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
let fs = admin.firestore();
let auth = admin.auth();
const listAllUsers = async (nextPageToken) => {
try {
let result = await auth.listUsers(100, nextPageToken);
result.users.forEach((userRecord) => {
start(userRecord.toJSON())
});
if (result.pageToken) {
listAllUsers(result.pageToken);
}
} catch(ex) {
console.log('Exception listing users:', ex.message);
}
}
async function first(){
await listAllUsers();
}
first();
async function start (object){
const info = await fs.collection('users').doc(object.uid).get();
if (!info.exists) {
console.log('No document');
} else {
console.table([info.data()]);
document.getElementById("greeting").innerHTML = info.data().toString();
}
}
HTML code:
<!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>
<script type="text/javascript" src="app3.js"></script>
</head>
<body>
<p id="greeting"></p>
</body>
</html>
but I want to send data console.log(info.data()) to HTML page to simply show information,
How can I do that, I don't want to use react or any other
can someone help me?
and I also is this Nodejs or plain javascript?
You can use innerHTML to sent data in your html.
Like this:
document.getElementById("yourElementId").innerHTML = info.data();
This is working for me:
<p id="greeting">
</p>
<script>
document.getElementById("greeting").innerHTML = "test"
</script>
I have made a flask app that detects the changes made in a log file like the tail-f command in UNIX, but when I run it and make changes in the log file the output is not displayed on the webpage, I have written the code with reference to this,
Here is my flask app
import time
import os
from flask import Flask, render_template
app=Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/logs')
def logs():
def generate():
with open("log.log") as f:
while True:
# read last line of file
line = f.readline()
# sleep if file hasn't been updated
if not line:
time.sleep(0.1)
continue
yield line
return app.response_class(generate(), mimetype='text/plain')
app.run(debug=True)
Here is the log file, just for the sake of simplicity I have created a dummy log file
like this
1
2
3
4
5
and here is the index.html file
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<pre id="output"></pre>
<meta charset="utf-8">
<title>Logs</title>
<p>LOGS</p>
<script>
var output = document.getElementById('output');
var xhr = new XMLHttpRequest();
xhr.open('GET', '{{ url_for('logs') }}');
xhr.send();
setInterval(function() {
output.textContent = xhr.responseText;
}, 1000);
</script>
</body>
</html>
Now when I run this Flask App nothing is diplayed on the localhost server, what am I doing wrong here, so that I can get the logs displayed without refreshing the webpage?
In my opinion you should use a reader to read the stream. This means that the end of the transmission is not waited for, but is read in piece by piece.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<pre id="output"></pre>
<script type="text/javascript">
(() => {
fetch('/logs')
.then(response => {
const elem = document.getElementById('output');
const reader = response.body.getReader();
const readStream = ({ done,value }) => {
if (done) {
return;
}
let chunk = String.fromCharCode.apply(null, value);
elem.textContent += chunk + '\n';
return reader.read().then(readStream);
};
reader.read().then(readStream);
});
})();
</script>
</body>
</html>
I am trying to upload audio data from a web page to a server and find it more difficult than it should be.
Here is my test page, it has a button and when it is clicked, a voice recording of 5 seconds starts, then it is played back and finally the sound data should be uploaded to the server.
The voice recording and play back parts are working fine.
The upload to the server is not completely working.
The code I have is totally visible below. I put the whole file (called "GetAudio.php") on purpose, so anyone can easily copy-paste it to try.
Here is what goes wrong: the file created on the server called "Audio.data", contains 4 characters, namely:
blob
This is not what I want. I want the file to contain the actual sound data that has been recorded locally. Can someone tell me where my code is missing some important thing?
<!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>Record&Upload Trial</title>
</head>
<body>
<div>
<h2>Five seconds voice record and upload.</h2>
<p>
<button id=startRecord><h3>Start the voice recording</h3></button><br/>
<audio id="player" controls></audio>
<p id="XMLH"></p>
</p>
</div>
<?php
// Server side code:
if ($_POST['AudioData']) {
$myfile = fopen("Audio.data", "w");
fwrite($myfile, $_POST['AudioData']);
fclose($myfile);
}
?>
<script>
startRecord.onclick = e => {
startRecord.disabled = true;
audioChunks = [];
rec.start();
setTimeout(() => {
rec.stop();
startRecord.disabled = false;
}, 5000);
}
var player = document.getElementById('player');
var handleSuccess = function(stream) {
rec = new MediaRecorder(stream);
rec.ondataavailable = e => {
audioChunks.push(e.data);
if (rec.state == "inactive") {
let blob = new Blob(audioChunks,{type:'audio/x-mpeg-3'});
player.src = URL.createObjectURL(blob);
player.controls=true;
player.autoplay=true;
// The code below intends to upload the sound file to the server.
// But it is partly (or completely) wrong and does not work.
var xhr = new XMLHttpRequest();
var params = 'AudioData=blob';
xhr.open('POST', 'GetAudio.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
}
}
};
navigator.mediaDevices.getUserMedia({audio:true})
.then(handleSuccess);
</script>
</body>
</html>
So, this is my JS code:
function main(){
let myJSON = parseCSV();
console.log(myJSON);
let myCSV = transformCSV(myJSON);
console.log(myCSV);
}
function parseCSV(){
let parsedJSON;
let selectedFile = document.getElementById('fileIn').files[0];
Papa.parse(selectedFile, {
complete: function(results) {
parsedJSON = results.data;
console.log(results.data);
console.log(typeof(results.data));
}
});
return parsedJSON;
}
function transformCSV(JSONIn){
let csvOut = ""; // i will do something here later
let dCol = ""; // i will do something here later
let dRow = ""; // i will do something here later
for (let i = 0; i < JSONIn.length - 1; i++) {
// i will do something here later
}
return csvOut;
}
And this is my test html page:
<!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>
</head>
<body>
<script src=".\transformCSV.js"></script>
<script src=".\node_modules\papaparse\papaparse.js"></script>
<input type="file" id="fileIn">
<input type="button" value="click!" onclick="main()">
</body>
</html>
When I try to read length of myJSON, I get error message in Chrome console: Uncaught TypeError: Cannot read property 'length' of undefined. Why is it undefined? It is present in console! Why does this happen and how to fix it? How to work with resulted myJSON as a perfectly normal static JSON?
You set the value of parsedJSON in the complete callback function. This will probably be called AFTER your function parseCSV has returned the undefined value of parsedJSON. You need to rewrite it with a callback or promise.
parseCSV(function (myJSON) {
console.log(myJSON);
let myCSV = transformCSV(myJSON);
console.log(myCSV);
});
function parseCSV(callback){
let parsedJSON;
let selectedFile = document.getElementById('fileIn').files[0];
Papa.parse(selectedFile, {
complete: function(results) {
parsedJSON = results.data;
callback(parsedJSON);
}
});
}