Edit Table Localstorage and Javascript/Jquery - javascript

I need to edit the table stored in localStorage and json, how could it? I'm new and I could only save but not to edit these items in the table.
Javascript and Jquery
$( document ).ready(function() {
cargarDatos();
//document.getElementById('btnGuardar').onclick = mostrarDatos;
$('#frmContacto').submit(function(event) {
event.preventDefault(); //Bloqueo de comportamiento por defecto de formulario
guardarDatos();
cargarDatos();
});
$('input').on('blur', function(){
$(this).addClass('marcado');
});
$('.btnEditar').on('click', function(event){
event.preventDefault(); //Bloqueo de comportamiento por defecto de formulario
id = this.id;var link = this.href;
alert(link);
id = link.substr(link.indexOf("#"), link.length);
alert(id);
editarDatos();
});
$('#inputFoto').on('change', function(e) {
precargarImagen(this);
});
});
//Colección de contactos
//var contactos = new Array();
function guardarDatos(){
name = $('#inputNombre').val();
direccion = $('#inputDireccion').val();
telefono = $('#inputTelefono').val();
fecha = $('#inputFecha').val();
email = $('#inputEmail').val();
color = $('#inputColor').val();
dataFoto = $("#imgFoto").attr("src");
contacto = {
nombre : name,
direccion : direccion,
telefono : telefono,
fecha : fecha,
email : email,
color : color,
foto : dataFoto
};
contactos.push(contacto);
console.log(JSON.stringify(contactos));
localStorage.setItem('lstcontactos2', JSON.stringify(contactos));
}
function cargarDatos(){
var data = localStorage.getItem('lstcontactos2');
contactos = data && JSON.parse(data);
if(contactos==null)
contactos = new Array();
$('#tablaContactos').bootstrapTable({
data: contactos
});
}
/**
* Formato asociado a tabla boostrapTable para el campo de acciones, con la finalidad
* que asocie un boton para editar la tarea que posterior sera capturado en el evento clic
* #param value Id de la tarea
*/
function btnEditar(value){
console.log("valueformat " + value);
return '<span class="glyphicon glyphicon-pencil"></span>';
}
function imgFoto(value){
return '<img id="imgFoto" src="' + value +
'" style="width:auto;height:160px;">';
}
/**
* Recupera del input:file el archivo seleccionado y lo renderiza en la pantalla
* #param inputfile Objeto input de tipo file sobre el que se esta seleccionado la imagen
*/
function precargarImagen(inputfile){
var file = inputfile.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = reader.result;
$(".file-caption-name").html(file.name);
$(".file-preview-frame").empty();
$(".file-preview-frame").
append('<img id="imgFoto" src="' + reader.result +
'" style="width:auto;height:160px;">');
};
reader.readAsDataURL(file);
inputfile.val(img.src);
} else {
alert("Archivo no soportando!");
}
}
How i did? Examples? i'm new please.

Related

Why the output video file in my script javascript is null

I am trying to understand why in the following javascript program the output video file is null, indeed the gold of the download the video file contains no data, here is the program in question:
let videoStream;
navigator.mediaDevices.getUserMedia({ video: true }).then(function (stream) {
videoStream = stream;
const mediaRecorder = new MediaRecorder(videoStream, { mimeType: "video/webm" });
let recordedBlobs = [];
mediaRecorder.ondataavailable = function (event) {
if (event.data && event.data.size > 0) {
recordedBlobs.push(event.data);
}
};
mediaRecorder.start();
setTimeout(() => {
mediaRecorder.stop();
// Créez un fichier blob à partir des données enregistrées
const blob = new Blob(recordedBlobs, { type: "video/webm" });
// Créez un lien vers le fichier blob
const url = URL.createObjectURL(blob);
// Créez une balise "a" avec un lien vers le fichier blob et un attribut "download"
const link = document.createElement("a");
link.href = url;
link.download = "mon-fichier.webm";
// Ajoutez la balise "a" au document
document.body.appendChild(link);
// Cliquez sur le lien pour déclencher le téléchargement
link.click();
// Supprimez le lien du document une fois le téléchargement terminé
link.parentNode.removeChild(link);
}, 15000);
});
I tried to extend the time of the video and transform the script with on and off buttons but it still didn't work

Generate a CSV file from a JSON object

It's all in the title, I would like to generate a CSV file from the JSON objet get from this Ajax request,
The JSON I get represent all the recordings from a form :
I already have something that work for one field value a a single recording (the 0 here) :
<!DOCTYPE html>
<meta charset="utf-8"/>
<html>
<head>
<title>This is Website Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" type="text/javascript"></script>
<script src="../FileSaver.js"></script>
<script>
var formId = 566091
// Définition des paramètres de la requête HTTP
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.kizeoforms.com/rest/v3/forms/"+formId+"/data/readnew",
"method": "GET",
"headers": {
"content-type": "application/json",
"Authorization": "******",
}
}
// Envoi de la requête et affichage en console de la réponse
$.ajax(settings).done(function (response) {
console.log(response);
var ssa3 = [];
for (var i = 0 ; i <= response.data.length; i++) {
ssa3.push(response.data[i].fields.ssa_3_a_22h00.value);
}
//var ssa3 = response.data[0].fields.ssa_3_a_22h00.value;
var blob = new Blob([ssa3], {type: "application/csv;charset=utf-8"});
saveAs(blob, "ssa3.csv");
});
</script>
</head>
</html>
I would now like to have this field value for all the recordings, I have tried to push it into a table but console tells me "i is undefined"
$.ajax(settings).done(function (response) {
console.log(response);
var ssa3 = [];
for (var i = 0 ; i <= response.data.length; i++) {
ssa3.push(response.data[i].fields.ssa_3_a_22h00.value);
}
var blob = new Blob([ssa3], {type: "application/csv;charset=utf-8"});
saveAs(blob, "ssa3.csv");
});
Finally found it, I used a forEach to browse the data :
$.ajax(settings).done(function (response) {
console.log(response);
var ronde1n = [];
//on définit data qu'on va devoir parcourir avec un forEach
const data = response.data;
//on envoie les headers du fichiers csv
ronde1n.push("Numéro d'enregistrement,ID,Date et heure,conso SSA3");
//on parcours l'ensemble des enregistrements du formulaire Ronde 1 nuit
data.forEach(function (i) {
//on envoie les valeurs des champs qui nous intéressent pour chaque enregistrement
ronde1n.push("\r\n" + i.record_number + "," + i.id + "," + i.fields.date_et_heure.value + "," + i.fields.ssa_3_a_22h00.value);
});
//création du fichier CSV
var blob = new Blob([ronde1n], {type: "application/csv;charset=utf-8"});
saveAs(blob, "ronde1_nuit.csv");
});

Load wav local file into WebAudio

I want to load a .wav file which I have loaded like this:
var selectedFile = document.getElementById('input').files[0];
I want to load it into an AudioContext for using it later as an stream source for my WebRTC application.
I have tried using File reader to read as ArrayBuffer for later loading with DecodeAudioData into the context, but I don't get that to work.
Thanks in advance.
EDIT:
I have tried like this
var selectedFile = document.getElementById('input').files[0];
//Creamos el lector de fichero
var reader = new FileReader();
//Leemos el fichero como un buffer
reader.readAsArrayBuffer(selectedFile);
// Esperamos a que termine de leer
while (reader.readyState !=2){
}
//Guardamos el resultado de la lectura
var buffer= reader.result;
//Creamos el contexto que luego introducira el audio en el peer
var context = new AudioContext();
context.decodeAudioData(buffer, function(audio) {
var AudioBuffer=audio;
},
function(e){"Error with decoding audio data" + e.err});
and like this
var selectedFile = document.getElementById('input').files[0];
//Creamos el lector de fichero
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = function () {
var data = reader.result;
var buffer = new Int8Array(data);
output.value = JSON.stringify(array, null, ' ');
window.setTimeout(ReadFile, 1000);
};
reader.readAsArrayBuffer(selectedFile);
//Guardamos el resultado de la lectura
var buffer= reader.result;
console.log("Guarda resultado de la lectura");
//Creamos el contexto que luego introducira el audio en el peer
var context = new AudioContext();
console.log("Contexto creado");
context.decodeAudioData(buffer, function(audio) {
console.log("Descodificado");
var AudioBuffer=audio;
console.log("asignado");
},
function(e){"Error with decoding audio data" + e.err});

function call in node js using socket

I'm trying to call a function which is created in another "class", and I want to use it in the socket.on (...) but it is not working , it keeps showing
this.function is not a function.
here is the code
//calling the function
Serveur.prototype.traitementSurConnection = function(socket) {
var that = this
socket.on('connection', function (creator, typeArtifact,idConteneur, typeConteneur) {
that.addArtifact('momo', 'img', 1,0);
})
};
//the function
ZoneCollaborative.prototype.addArtifact = function(creator, typeArtifact,idConteneur, typeConteneur) {
// calcul d'un nouvel identifiant
var id = this.setIdAr();
console.log(' *** ZC : calcul nouveau IdArtifact = '+id);
// création de l'artifact
var monArtifact = new Artifact(id, creator, typeArtifact, idConteneur,
typeConteneur);
console.log(' *** ZC : creation artifact'+monArtifact.getId() );
// ajout à la liste
this.artifacts.push(monArtifact);
console.log(' *** ZC : total artifact ='+ this.artifacts.length);
};
here is the ful code of bothe Serveur.js and ZoneCollaborative.js
//Serveur.js
var http = require('http');
var socket = require('socket.io');
var ZP = require('./ZonePartage');
var Constantes = require('./Constante');
//création des constantes
var CONSTANTE = new Constantes();
function Serveur(ZP, port) {
this.ZP = ZP;
this.port = port;
console.log(" ---- Creation d'un serveur pour la ZP (" + ZP.getId()
+ ") sur le port " + port);
var serveur = http.createServer(function(req, res) {
});
serveur.listen(this.port, function() {
console.log(' ---- Server en ecoute sur port ' + port);
});
//
var io = require('socket.io').listen(serveur);
console.log(' ---- Socket en ecoute sur port ' + port);
browser = require('iotdb-arp');// module qui s'occupe de la determination de l'adress MAC
io.sockets.on('connection', (function(socket) {
console.log(' ---- Socket connection');
console.log('un utilisateur est connecté');
browser.browser({}, function(error, d) {
if (error) {
console.log("#", error);
} else if (d) {
var adresse = d.ip;
console.log('son adresse ip est ' + adresse); //obtenir l'adress ip de l'utilisateur connecté
}
});
socket.on('disconnect', function() {
console.log(' ==> 1 utilisateur déconnecté <== '); //déconnection
});
this.traitementSurConnection(socket);
}).bind(this));
console.log(' ---- Socket en attente de traitement port ' + port);
}
module.exports = Serveur;
Serveur.prototype.demandConnexion = function(idZEP) {
if (this.ZP.createZE(idZEP))
{
console.log(' ==> socket : demande de creation ZE pour ' + idZEP
+ ' accepte');
}
else
{
console.log(' ==> socket : demande de creation ZE pour ' + idZEP
+ ' refuse');
}
};
Serveur.prototype.traitementSurConnection = function(socket) {
console.log(' ==> socket connexion');
var self = this;
socket.on('connection', function(creator, typeArtifact, idConteneur,
typeConteneur) {
self.addArtifact('momo', 'img', 1, 0);
})
}
});
//ZoneCollaborative.js
ZoneCollaborative.prototype.addArtifact = function(creator, typeArtifact,idConteneur, typeConteneur) {
// calcul d'un nouvel identifiant
var id = this.setIdAr();
console.log(' *** ZC : calcul nouveau IdArtifact = '+id);
// création de l'artifact
var monArtifact = new Artifact(id, creator, typeArtifact, idConteneur,
typeConteneur);
console.log(' *** ZC : creation artifact'+monArtifact.getId() );
// ajout à la liste
this.artifacts.push(monArtifact);
console.log(' *** ZC : total artifact ='+ this.artifacts.length);
};

Working with blob, XMLHttpRequest and WebSQL - Trying to save blob into WebSQL and then recover to window.URL.createObjectURL

it's my frist question here on stackoverflow. I tryed search here and at Google ways to:
Convert file into blob, save it in WebSQL, then select it from the database and shows with window.URL.createObjectURL
So... Almost everything is done I've already converted to blob with XMLHttpRequest saved into WebSQL (I've chosen WebSQL for mobile use purpose) but I don't figure out how to get the binary text re-converted to blob and open with window.URL.createObjectURL. I've already tried several ways to do that including using Blob builder, it writes the URL but with nothing (404 error)
Here follows my code, the comments are in portuguese, but any question, just ask.
I set the query to ID=1 and result[0] just to test.
<script>
window.URL = window.URL || window.webkitURL; //Instancia o window.URL
var xhr = new XMLHttpRequest(); //Instancia o XHMLHttpRequest
window.onload = function(){
var status = document.getElementById("status");
status.innerHTML = "Aplicação Carregada";
potti.webdb.open();//Abre o Banco
potti.webdb.createTable();//Cria a tabela
getBinary("http://www.belenosonline.com/Blob/1.pdf");//Pega o arquivo
}//Fim onload
function getBinary(url){
if(xhr != null){//Se ele conseguir criar o HMLHttpRequest
xhr.open("GET", url, true);//Abre a conexão GET para o arquivo de forma assincrona (true)
xhr.responseType = "text";
xhr.onreadystatechange = xhrHandler;//State Handler
xhr.send(null);//Não envia nada
}
else{
alert("Seu navegador não é suportado, por favor, atualize-o");
}
}
xhrHandler = function(){
if(xhr.readyState == 3){
status.innerHTML = "Carregando Arquivo";
}
else if(xhr.readyState == 4){
if(xhr.status == 200){
status.innerHTML = "Arquivo Carregado com Sucesso";
var conteudo = xhr.responseText;
potti.webdb.insert("Mozilla",conteudo);
}
else{
status.innerHTML = "Houve um erro no processamento do arquivo";
}
}
else{
status.innerHTML = "Houve um erro no processamento do arquivo";
}
}
//Encapsula o Banco de dados
var potti = {};
potti.webdb = {};
potti.webdb.db = null;
//Abre o BD
potti.webdb.open = function() {
var dbSize = 50 * 1024 * 1024; // 50MB
potti.webdb.db = openDatabase("TestBD", "1.0", "Teste", dbSize);
}
//Cria a tabela no banco
potti.webdb.createTable = function() {
var db = potti.webdb.db;
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS TestTable(ID INTEGER PRIMARY KEY ASC, nome TEXT ,conteudo TEXT)", []);
});
}
//Insere dados no Banco
potti.webdb.insert = function(nome,conteudo){
var db = potti.webdb.db;
db.transaction(function(tx){
status.innerHTML = "Gravando no Banco";
tx.executeSql("INSERT INTO TestTable(nome, conteudo) VALUES (?,?)",
[nome, conteudo],
potti.webdb.onSuccess,
potti.webdb.onError);
});
}
//Carrega dos dados
potti.webdb.loadData = function() {
var db = potti.webdb.db;
var result = [];
db.transaction(function (tx) {
tx.executeSql("Select * TestTable WHERE ID = 1", [], function(tx, rs){
for(var i=0; i<rs.rows.length; i++) {
var row = rs.rows.item(i);
result[i] = {
"Id" : row["ID"],
"Nome" : row["nome"],
"Conteudo" : row["conteudo"],
};
}
var blob = new Blob([result[0].Conteudo], { type: 'application/pdf' });
console.log(window.URL.createObjectURL(blob));
}, potti.webdb.onError);
});
}
//Erro no Banco de Dados
potti.webdb.onError = function(tx, e) {
console.log("Houve um erro " + e.message);
}
//Sucesso no Banco de Dados
potti.webdb.onSuccess = function(tx, r) {
document.getElementById("status").innerHTML = "Salvo no Banco";
potti.webdb.loadData();
}
</script>
after 2 weeks trying I got it with a issue here on stackoverflow: Retrieving binary file content using Javascript, base64 encode it and reverse-decode it using Python
You have to get a Arraybuffer > Convert to Base64 > Store > Get > Decode to ArrayBuffer > Create Blob

Categories