Creating an image file dynamically with Javascript - javascript

I'm trying to create an image file dynamically, based on the contents retrieved from S3 Bucket. Got CORS working fine, here's the code I've written:
/**
* #name fetchFile
* #desc Fetch the desired file, and add to our _filesPending array, and update dialog process
* #author cgervais
*/
var _filesPending = [];
var _fileMessageDialog = "Currently downloading {{numberOfFiles}} videos...";
var _filesDownloadedSoFar = 0;
var _filesDownloaded = [];
var downloading = false;
function OKDownload(response, fileName) {
var responsePerfect = {
link: function() {
var _tmpResponse = JSON.parse(response);
return _tmpResponse.location;
}
};
$.ajax({
type: "GET",
url: responsePerfect.link(),
data: {},
success: function(answer) {
var _tmpFileObject = {
fUrl: fileName,
fContent: btoa(unescape(encodeURIComponent(answer.trim())))
};
_filesDownloaded.push(_tmpFileObject);
_filesDownloadedSoFar = _filesDownloadedSoFar + 1;
console.log('Downloaded -- so far: ' + _filesDownloadedSoFar);
},
error: function(response, errorCode, errorMessage) {
console.log('[OKDownload] ' + response + ' - ' + errorCode + ' - ' + errorMessage + ' // ' + responsePerfect.link);
}
})
}
var _alreadyGeneratedRStrings = [];
function generateReasonableString(min, max, fnMax) {
var _genStringSeed = Date.now() + 10;
var _randomString = '';
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=min; i < max; i++ )
{
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
_randomString = btoa(text + '::' + _genStringSeed);
if(_randomString.indexOf('==') > -1) {
_randomString = _randomString.replace('==','');
}
if(_randomString.length > fnMax) {
_randomString = _randomString.substring(0, fnMax);
}
if(_alreadyGeneratedRStrings.indexOf(_randomString) > -1) { _randomString = generateReasonableString(min, max, fnMax); }
_alreadyGeneratedRStrings.push(_randomString);
return _randomString;
}
function httpRawFetch(link) {
var matched = generateReasonableString(8, 26, 8) + ".jpg";
$.ajax({
type: "GET",
url: link.href + "&rawlink=yes",
data: {},
success: function(answer) {
if(answer === "") { console.log('[httpRawFetch] Failed fetching ' + link); return; }
OKDownload(answer, matched);
},
error: function(response, errorCode, errorMessage) {
console.log('[httpRawFetch] Error fetching JSON data from backend server.');
console.log('[DEBUG] ' + response + ' - ' + errorCode + ' - ' + errorMessage);
console.log('[DEBUG] Link: ' + link);
}
})
}
function generateDownloadModal() {
var _tmpHTML;
// #TODO: generate side modal with jQuery
}
function downloadFinished() {
var zip = new JSZip();
var _runningCountOfFiles = 0;
var _runningAddFiles = true;
for(var i = 0; i < _filesDownloaded.length; i++) {
_runningAddFiles = true;
// zip create file ( fileName, fileContent )
zip.file(_filesDownloaded[i].fUrl, decodeURIComponent(escape(atob(_filesDownloaded[i].fContent))));
_runningCountOfFiles++;
}
var recInterval = setInterval(function() {
if(_runningAddFiles && _runningCountOfFiles == _filesDownloaded.length || _runningCountOfFiles > _filesDownloaded.length) {
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "recordings.zip");
_runningAddFiles = false;
clearInterval(recInterval);
});
}
}, 1000);
}
setInterval(function() {
if(downloading) {
if(_filesDownloadedSoFar === _filesDownloaded.length) {
downloadFinished();
downloading = false;
}
}
}, 60000);
function fetchFile(link) {
if(link === "") {
alert('Cannot download this file.');
return;
}
_filesPending.push(link);
httpRawFetch(link);
downloading = true;
}
The issue:
It creates the zip with files, then it downloads to my machine. I open the image file, I get an error (all of them): "We can't open this file"
What am I doing wrong? They're JPG images.

Related

Debugger not reaching select statement in jQuery.autocomplete

I have a Dynamic Grid in the ASP.NET page. When I click Add User, it creates an empty record with Textbox controls and when the user types something in the first Textbox - UserName, it should pull the UserNames from the Database and autocomplete should work for that Textbox control.
I have implemented jQuery.autocomplete function as below.
jQuery("#" + e.id).autocomplete({
source: function (request, response) {
var txtSearch = jQuery("#" + e.id).attr("id");
var t = jQuery("#" + txtSearch).val();
var URL = "../Users.aspx?UserName=" + t;
jQuery.ajax({
url: URL,
success: function (data) {
switch (data) {
case 'NOVALUESFOUND':
var rftspanID = e.id.replace("txt", "span");
break;
default:
var rftspanID = e.id.replace("txt", "span");
var rows = data.split("|");
var jsStr = "var datalist=[";
for (i = 0; i < rows.length - 1; i++) {
var s = rows[i].toString();
s = s.replace("'", "\\'");
s = s.replace('"', "\\'");
var row = s.split("~");
jsStr += "{id:'" + row[0].toString() + "'";
jsStr += ",name:'" + row[1].toString() + "'},";
}
jsStr = jsStr.slice(0, jsStr.length - 1);
jsStr += "];";
eval(jsStr);
if (typeof (datalist) != 'undefined') {
response(jQuery.map(datalist, function (items) {
if (items.id != undefined) {
return {
value: items.name,
id: items.id
}
}
}));
}
}
}
});
},
minlength: 1,
select: function (event, ui) {
if (Type == 1) {
document.getElementById("txtUser" + MemCount).value = ui.item.value;
}
else if (Type == 2) {
document.getElementById("txtRole" + MemCount).value = ui.item.value;
}
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function (event) {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
When I try to Debug this autocomplete, the data is coming at the end of response(jQuery.map(datalist, function (items) statement. But the select: option is not firing.
EDIT
The below screenshot shows how the data is formed.
And this is what is present in the Server-Side Users.aspx.vb Page_Load Event
Response.Clear()
Response.Write(GetUserName(Request.QueryString("UserName")))
Response.End()
What could be the problem?
First. In the response, you check the data variable in swith. And you get it as a string.
Second. the best way to work with ajax is JSON.
jQuery.ajax({
url: url,
dataType: 'json'
On successful response:
Make parsing.
json = JSON.parse(data)
And then you already apply your logic, I work with individual object variables.
swith(json.string){ .... }
And it will be easier to fill Textbox controls with the necessary parameters: json.user - the variable will contain an array of data about users.
Update code:
jQuery("#" + e.id).autocomplete({
source: function (request, response) {
var txtSearch = jQuery("#" + e.id).attr("id");
var t = jQuery("#" + txtSearch).val();
var URL = "../Users.aspx?UserName=" + t;
jQuery.ajax({
url: URL,
dataType: 'json',
/*
* format respone data (string!!!) -> {"result": [{"id": 1,"item": 2},{"id": 1,"item": 2}],"found": "VALUESFOUND"}
*/
success: function (data) {
let json = JSON.parse(data);
switch (json.found) {
case 'NOVALUESFOUND':
var rftspanID = e.id.replace("txt", "span");
break;
default:
var rftspanID = e.id.replace("txt", "span");
response(jQuery.map(json.result, function (items) {
if (items.id != undefined) {
return {
value: items.name,
id: items.id
}
}
}));
}
}
});
},
minlength: 1,
select: function (event, ui) {
if (Type == 1) {
document.getElementById("txtUser" + MemCount).value = ui.item.value;
}
else if (Type == 2) {
document.getElementById("txtRole" + MemCount).value = ui.item.value;
}
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function (event) {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});

How Do I add this javascript and HTML code into an angular project? and can i render html from javascript function in angular?

How Do I add this javascript and HTML code into an angular project ?
I have placed the func.js in a src folder in my angular project and in my app.component.ts file
where I tried to import and use ngAfterViewInit() to load and use the javascript functions
These are the javascript and html files I am trying to add to the angular web app:
funcs.js
const uName = 'admin';
const uPass = '12345';
const endpoint = 'http://11.11.111.241:8000';
const resource = {
questionnaire: 'Questionnaire',
valueset: 'ValueSet'
}
//get questionnaire
var url = 'http://cihi.ca/fhir/irrs/Questionnaire/abc-abc-community-on';
var quesJson = getData(resource.questionnaire, '?url=' + url);
quesJson = quesJson.entry[0].resource
// saveJsonToFile(quesJson, 'irrsQuesJson');
var copy = $.extend(true, {}, quesJson);
//convert to lhc form
var lformsQ = LForms.Util.convertFHIRQuestionnaireToLForms(quesJson, 'STU3')
// saveJsonToFile(lformsQ, 'lFormJson');
//prepare valuesets
const vsArray = createValueSetData();
//add value sets
injectValueSet(lformsQ);
// saveJsonToFile(lformsQ, 'lFormValueSetInjected');
// Add the form to the page
var options = { 'prepopulate': true };
LForms.Util.addFormToPage(lformsQ, 'formContainer', options);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getData(res, param, log) {
var data = null;
var url = endpoint + '/' + res + param;
$.ajax({
accepts: {
json: 'application/fhir+json',
xml: 'application/fhir+xml'
},
dataType: 'json',
type: 'GET',
url: url,
async: false,
success: function (response) {
data = response;
if (log)
console.log('getData: SUCCESS - "' + url + '"');
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(uName + ":" + uPass));
},
error: function (err) {
if (log)
console.error('getData: FAILED - "' + url + '"')
}
});
return data;
}
//recursively inject valueset into lhc json
function injectValueSet(lhcJson) {
if (lhcJson && 'items' in lhcJson) {
lhcJson.items.forEach(e => {
injectValueSet(e);
});
} else {
if ('answerValueSet' in lhcJson && 'reference' in lhcJson.answerValueSet) {
lhcJson['answers'] = vsArray[lhcJson.answerValueSet.reference];
}
}
}
//save form
function save() {
var quesResp = LForms.Util.getFormFHIRData('QuestionnaireResponse', 'STU3', '#formContainer');
saveJsonToFile(quesResp, 'questionnaireResponse' + '-' + new Date().getTime());
// var newLform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', quesResp, lformsQ, 'STU3');
// LForms.Util.addFormToPage(newLform, 'formContainer2');
}
//open file
function openQues() {
var file = $('#file1')[0].files[0];
const fileReader = new FileReader();
fileReader.onload = event => {
var data = JSON.parse(event.target.result);
var lform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', data, lformsQ, 'STU3');
injectValueSet(lformsQ);
LForms.Util.addFormToPage(lform, 'formContainer');
};
fileReader.onerror = error => console.error("Error loading file!");
fileReader.readAsText(file, "UTF-8");
}
// get valueSet count
function getValueSetCount() {
var count = 0;
var response = getData(resource.valueset, '?_summary=count');
if (response) {
count = response.total;
}
return count;
}
//get all valueSets id
function getValueSetIds() {
var ids = [];
var count = getValueSetCount();
var response = getData(resource.valueset, '?_count=' + count + '&_element=id');
if (response) {
if ('entry' in response && response.entry.length > 0) {
response.entry.forEach(e => {
if ('resource' in e && 'id' in e.resource && 'url' in e.resource) {
ids.push({
'id': e.resource.id,
'url': e.resource.url
});
}
});
}
}
return ids;
}
//create valueSet array for form fields
function createValueSetData() {
var data = {}, dataValueSet, failedIds;
var ids = getValueSetIds();
if (ids) {
failedIds = [];
ids.forEach(idSet => {
var response = getData(resource.valueset, '/' + idSet.id + '/$expand');
if (response && 'expansion' in response
&& 'contains' in response.expansion
&& response.expansion.contains.length > 0) {
dataValueSet = [];
response.expansion.contains.forEach(e => {
dataValueSet.push({
'text': e.code + ' - ' + e.display,
'code': e.code
});
});
data[idSet.url] = dataValueSet;
} else {
failedIds.push(idSet.id);
}
});
if (failedIds.length > 0) {
console.error("Failed fetching valueSets for the following IDs: \n Count: "
+ failedIds.length + "\n" + failedIds);
}
}
return data;
}
//save json to file
function saveJsonToFile(json, fileName) {
var textToSave = JSON.stringify(json);
var data = new Blob([textToSave], { type: 'text/plain' });
var textFileURL = window.URL.createObjectURL(data);
var hiddenElement = document.createElement('a');
hiddenElement.href = textFileURL;
hiddenElement.target = '_blank';
hiddenElement.download = fileName + '.txt';
hiddenElement.click();
}
**Html file :**
<!DOCTYPE html>
<html>
<head>
<link href="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/styles/lforms.min.css" media="screen"
rel="stylesheet" />
<link href="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.css"
rel="stylesheet" />
</head>
<body>
<button onclick="save()">
Save QuestionnaireResponse
</button>
<input type="file" id="file1">
<button onclick="openQues()">
Open QuestionnaireResponse
</button>
<div id="formContainer"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/lforms.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/fhir/STU3/lformsFHIR.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
first create a new component through angular cli and add the variable declarations in .ts file i.e
const uName = 'admin';
const uPass = '12345';
const endpoint = 'http://11.11.111.241:8000';
const resource = {
questionnaire: 'Questionnaire',
valueset: 'ValueSet'
}
//get questionnaire
var url = 'http://cihi.ca/fhir/irrs/Questionnaire/abc-abc-community-on';
var quesJson = getData(resource.questionnaire, '?url=' + url);
quesJson = quesJson.entry[0].resource
// saveJsonToFile(quesJson, 'irrsQuesJson');
var copy = $.extend(true, {}, quesJson);
//convert to lhc form
var lformsQ = LForms.Util.convertFHIRQuestionnaireToLForms(quesJson, 'STU3')
// saveJsonToFile(lformsQ, 'lFormJson');
//prepare valuesets
const vsArray = createValueSetData();
//add value sets
injectValueSet(lformsQ);
// saveJsonToFile(lformsQ, 'lFormValueSetInjected');
// Add the form to the page
var options = { 'prepopulate': true };
LForms.Util.addFormToPage(lformsQ, 'formContainer', options);
then in .html page add the html code
<button onclick="save()">
Save QuestionnaireResponse
</button>
<input type="file" id="file1">
<button onclick="openQues()">
Open QuestionnaireResponse
</button>
<div id="formContainer"></div>
and then add the functions inside tag in the html file
function getData(res, param, log) {
var data = null;
var url = endpoint + '/' + res + param;
$.ajax({
accepts: {
json: 'application/fhir+json',
xml: 'application/fhir+xml'
},
dataType: 'json',
type: 'GET',
url: url,
async: false,
success: function (response) {
data = response;
if (log)
console.log('getData: SUCCESS - "' + url + '"');
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(uName + ":" + uPass));
},
error: function (err) {
if (log)
console.error('getData: FAILED - "' + url + '"')
}
});
return data;
}
//recursively inject valueset into lhc json
function injectValueSet(lhcJson) {
if (lhcJson && 'items' in lhcJson) {
lhcJson.items.forEach(e => {
injectValueSet(e);
});
} else {
if ('answerValueSet' in lhcJson && 'reference' in lhcJson.answerValueSet) {
lhcJson['answers'] = vsArray[lhcJson.answerValueSet.reference];
}
}
}
//save form
function save() {
var quesResp = LForms.Util.getFormFHIRData('QuestionnaireResponse', 'STU3', '#formContainer');
saveJsonToFile(quesResp, 'questionnaireResponse' + '-' + new Date().getTime());
// var newLform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', quesResp, lformsQ, 'STU3');
// LForms.Util.addFormToPage(newLform, 'formContainer2');
}
//open file
function openQues() {
var file = $('#file1')[0].files[0];
const fileReader = new FileReader();
fileReader.onload = event => {
var data = JSON.parse(event.target.result);
var lform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', data, lformsQ, 'STU3');
injectValueSet(lformsQ);
LForms.Util.addFormToPage(lform, 'formContainer');
};
fileReader.onerror = error => console.error("Error loading file!");
fileReader.readAsText(file, "UTF-8");
}
// get valueSet count
function getValueSetCount() {
var count = 0;
var response = getData(resource.valueset, '?_summary=count');
if (response) {
count = response.total;
}
return count;
}
//get all valueSets id
function getValueSetIds() {
var ids = [];
var count = getValueSetCount();
var response = getData(resource.valueset, '?_count=' + count + '&_element=id');
if (response) {
if ('entry' in response && response.entry.length > 0) {
response.entry.forEach(e => {
if ('resource' in e && 'id' in e.resource && 'url' in e.resource) {
ids.push({
'id': e.resource.id,
'url': e.resource.url
});
}
});
}
}
return ids;
}
//create valueSet array for form fields
function createValueSetData() {
var data = {}, dataValueSet, failedIds;
var ids = getValueSetIds();
if (ids) {
failedIds = [];
ids.forEach(idSet => {
var response = getData(resource.valueset, '/' + idSet.id + '/$expand');
if (response && 'expansion' in response
&& 'contains' in response.expansion
&& response.expansion.contains.length > 0) {
dataValueSet = [];
response.expansion.contains.forEach(e => {
dataValueSet.push({
'text': e.code + ' - ' + e.display,
'code': e.code
});
});
data[idSet.url] = dataValueSet;
} else {
failedIds.push(idSet.id);
}
});
if (failedIds.length > 0) {
console.error("Failed fetching valueSets for the following IDs: \n Count: "
+ failedIds.length + "\n" + failedIds);
}
}
return data;
}
//save json to file
function saveJsonToFile(json, fileName) {
var textToSave = JSON.stringify(json);
var data = new Blob([textToSave], { type: 'text/plain' });
var textFileURL = window.URL.createObjectURL(data);
var hiddenElement = document.createElement('a');
hiddenElement.href = textFileURL;
hiddenElement.target = '_blank';
hiddenElement.download = fileName + '.txt';
hiddenElement.click();
}
and importantly add all the script imports to index.html the main index which is outside the app folder
add this in head section -
<link href="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/styles/lforms.min.css" media="screen"
rel="stylesheet" />
<link href="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.css"
rel="stylesheet" />
as well as this -
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/lforms.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/fhir/STU3/lformsFHIR.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.js"></script>
<script src="./index.js"></script>
last but not least add the selector of the created component in the app.component.html file
it should look something like this in created component of .html file add this to app.component.html
import { Component, OnInit } from '#angular/core';
import * as $ from 'jquery';
import {OpenQues,save} from '../assets/scripts.js'
declare var tesing: any;
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Look jQuery Animation working in action!';
public ngOnInit()
{
$.getScript('./assets/scripts.js');
}
public open()
{
OpenQues();
}
public save()
{
save();
}
}
This worked for me

Join multiple room in kurento

I want to create an application that allows a user to join multiple video call rooms in kurento.
I wrote the following code:
function joinRooms() {
var userId = document.getElementById('expertid').value;
console.log("UserID = " + userId);
var roomIds = document.getElementById('roomids').value.split(",");//Assume that we have 2 rooms r1 & r2
var userIdAlias = [];
for (var i = 0; i < roomIds.length; i++) {
userIdAlias[i] = userId + "(" + i + ")";
console.log("User alias = " + userIdAlias[i]);
}
var wsUri = 'wss://' + location.host + '/room';
kurento = KurentoRoom(wsUri, function(error, kurento) {
if (error)
return console.log(error);
for (let i = 0; i < roomIds.length; i++) {
//console.log("Start loop Roomid = " + roomId);
rooms[i] = kurento.Room({
room : roomIds[i],
user : userIdAlias[i],
subscribeToStreams : true
});
localStreams[i] = kurento.Stream(rooms[i], {
audio : true,
video : true,
data : true
});
localStreams[i].addEventListener("access-accepted", function() {
var playVideo = function(stream) {
var participantId = stream.getParticipant().getID();
var userId = document.getElementById('expertid').value;
console.log("userId = " + userId + ", participantId = " + participantId);
if (!userIdAlias.includes(participantId)) {
var elementId = "video-" + stream.getGlobalID();
var div = document.createElement('div');
div.setAttribute("id", elementId);
document.getElementById("participants").appendChild(div);
stream.playThumbnail(elementId);
// Check color
var videoTag = document.getElementById("native-" + elementId);
var userId = stream.getGlobalID();
var canvas = document.createElement('CANVAS');
checkColor(videoTag, canvas, userId);
}
}
rooms[i].addEventListener("room-connected", function(){
var j = i;
return function(roomEvent) {
document.getElementById('room-header').innerText = 'ROOM \"'
+ roomIds[j] + '\"';
//document.getElementById('join').style.display = 'none';
document.getElementById('room').style.display = 'block';
localStreams[j].publish();
var streams = roomEvent.streams;
for (var streamsIdx = 0; streamsIdx < streams.length; streamsIdx++) {
playVideo(streams[streamsIdx]);
}
}
});
rooms[i].addEventListener("stream-added", function(streamEvent) {
playVideo(streamEvent.stream);
});
rooms[i].addEventListener("stream-removed", function(streamEvent) {
var element = document.getElementById("video-"
+ streamEvent.stream.getGlobalID());
if (element !== undefined) {
element.parentNode.removeChild(element);
}
});
playVideo(localStreams[i]);
rooms[i].connect();
});
localStreams[i].init();
}
});
}
However, the code does not work. The log in server said that there is only one user request to join room r2 but not r1.
I think the reason is Javascript works with too many asynchronous task so it worked incorrectly.
Can you give some advice about the way to joining multiple rooms in kurento?

How to deal with asynchronous problems in javascript

I want to display data stored in ch ! But my problem is that ch is displayed before the data is stored !
I think this is an Asynchronous Problems! How can I solve this problem.
When I try to get length of ch, I get always 0. Even if I store data statically in ch, I get the length 0.
I think this is an Asynchronous Problems! How can I solve this problem.
function RechercheFiltrée() {
var nom = document.getElementById('nompre').value;
var matricule = document.getElementById('matcle').value;
$.ajax({
url: "myWebServiceURL",
type: "GET",
dataType: "xml",
success: function(xml) {
var stock = [];
$(xml).find('Population').each(function() {
var table = document.getElementById("myTable");
$(this).find("directories").each(function()
{
dossier = $(this).attr('dossier');
stock.push(dossier);
});
});
var ch = [];
for (var i = 0; i < stock.length; i++) {
$.ajax({
url: "/mySecondWebServiceURL" + stock[i],
type: "GET",
dataType: "xml",
success: function(xml) {
var NMPRES = "";
var jsonObj = JSON.parse(xml2json(xml, ""));
var nom = jsonObj.SubmitResponse.occurrences.occurrence.filter(x => x["#datasection"] === "TS")[0].data.filter(x => x.item === "NMPRES")[0].value;
var matcle = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0].data.filter(x => x.item === "MATCLE")[0].value;
var dossier = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0]["#dossier"];
ch.push({
"nom": nom,
"matcle": matcle,
"dossier": dossier
});
if ($('#population').val() != null && firstIter == false) {
}
},
error: function(request, error) {
console.log('error Connexion : ' + error + ' request Connexion : ' + request);
}
});
}
var txt = "";
var firstIter = true;
for (var key in ch) {
if (ch[key].matcle === matricule) {
txt += "<option value='" + ch[key].dossier + "'" + firstSelect(firstIter) + ">" + ch[key].nom + "</option>";
firstIter = false;
}
}
$('#population').html(txt)
},
error: function(request, error) {
console.log('error Connexion : ' + error + ' request Connexion : ' + request);
}
});
}
The problem is that you are not waiting for the second service to respond.
It should be something like this:
const deferreds = stock.map((stockItem) => {
//... your logic with ch.push here
return $.ajax({
// your call to the second service
});
});
$.when(...deferreds).then(() => {
// your code
// for (var key in ch) {
});
The approach I'd rather take is to break the code down and use Promises. You really should take your time to learn Promises. It's a JavaScript standard and what jQuery uses under the hood.
function RechercheFiltrée() {
var nom = document.getElementById('nompre').value;
var matricule = document.getElementById('matcle').value;
return $.ajax({
url: "myWebServiceURL",
type: "GET",
dataType: "xml"
});
}
function getStockArray(xml) {
var stocks = [];
$(xml).find('Population').each(function() {
var table = document.getElementById("myTable");
$(this).find("directories").each(function() {
{
dossier = $(this).attr('dossier');
stocks.push(dossier);
});
});
});
return stocks;
}
function getStocks(stocks) {
return Promise.all(stocks.map(fetchStock));
}
function fetchStock (stock) {
return $.ajax({
url: "/mySecondWebServiceURL" + stock,
type: "GET",
dataType: "xml"
})
.then(formatStockInfo)
}
function formatStockInfo (xml) {
var NMPRES = "";
var jsonObj = JSON.parse(xml2json(xml, ""));
var nom = jsonObj.SubmitResponse.occurrences.occurrence.filter(x => x["#datasection"] === "TS")[0].data.filter(x => x.item === "NMPRES")[0].value;
var matcle = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0].data.filter(x => x.item === "MATCLE")[0].value;
var dossier = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0]["#dossier"];
if ($('#population').val() != null && firstIter == false) {
}
return {
"nom": nom,
"matcle": matcle,
"dossier": dossier
};
}
function updateSelectMenu (ch) {
var txt = "";
var firstIter = true;
for (var key in ch) {
if (ch[key].matcle === matricule) {
txt += "<option value='" + ch[key].dossier + "'" + firstSelect(firstIter) + ">" + ch[key].nom + "</option>";
firstIter = false;
}
}
$('#population').html(txt)
}
RechercheFiltrée()
.then(getStockArray)
.then(getStocks)
.done(updateSelectMenu);

Error: SecurityError: DOM Exception 18 Tizen

I'm trying to insert data in my local database. When I get to opening the db it give me that error. I searched and found that it must be in a try catch block. I did it but still the same problem.
var APP_ID = "C44F83E2-6CCA-9BAD-FF5A-CE8C869F7300";
var SECRET_KEY = "39C7F777-F0A0-4DEB-FF35-D147FB5BEB00";
var VERSION = "v1";
var categories = [] ;
var createStatement = "CREATE TABLE IF NOT EXISTS categories(id INT NOT NULL PRIMARY KEY"
+",name VARCHAR(36) NOT NULL "
+",iconName VARCHAR(20) NOT NULL"
+",category VARCHAR(19) NOT NULL"
+",score INT NOT NULL)";
var selectAllStatement = "SELECT * FROM categories";
var insertStatement = "INSERT INTO categories(name,category,iconName,score) VALUES (?,?,?,?)";
var dropStatement = "DROP TABLE categories";
var current_item=0;
var total_item=2;
var db;
//database varsion setting
var version = 1.0;
//database name setting
var dbName = "GuessWhat";
//database display name setting
var dbDisplayName = "Guess_What_db";
//database size setting
var dbSize = 2 * 1024 * 1024;
function selectDB() {
if (window.openDatabase) {
//openDatabase(name, version, displayname, estimatedsize, callback);
try {
db = openDatabase(dbName, version, dbDisplayName, dbSize);
} catch (e) {
// TODO: handle exception
console.log(e);
}
dropTable(db);
createTable(db);
console.log("test base");
for(var c in categories)
{console.log(categories[c].getName());
insertData(db,categories[c].getName()+"",categories[c].getCategory()+"",categories[c].getIconName()+"",categories[c].getScore());
}
//inserting data in table
console.log("success");
} else {
alert("Web SQL Database not supported in this browser");
}
};
function createTable(db) {
try {
db.transaction(function (t) {
t.executeSql(createStatement, []);
});
} catch (e) {
// TODO: handle exception
}
};
function insertData(db, name,category ,iconName,score) {
try {
db.transaction(function (e) {
console.log("start insert");
e.executeSql(insertStatement,[name,category,iconName,score], onSuccess, onError);
});
} catch (e) {
// TODO: handle exception
console.log(e);
}
};
function onSuccess(e) { };
function onError(e) {console.log("erreur insertion"); };
function dropTable(db) {
try {
db.transaction(function (e) {
e.executeSql(dropStatement);
});
} catch (e) {
// TODO: handle exception
}
};
window.onload = function () {
// TODO:: Do your initialization job
Backendless.initApp( APP_ID, SECRET_KEY, VERSION );
fetchingFirstPageAsync();
selectDB();
// add eventListener for tizenhwkey
document.addEventListener('tizenhwkey', function(e) {
if(e.keyName == "back")
try {
tizen.application.getCurrentApplication().exit();
} catch (ignore) {
}
});
navigation("DOWN");
document.addEventListener('keydown', function(e) {
switch(e.keyCode){
case TvKeyCode.KEY_LEFT: //LEFT arrow
break;
case TvKeyCode.KEY_UP: //UP arrow
navigation("UP");
break;
case TvKeyCode.KEY_RIGHT : //RIGHT arrow
break;
case TvKeyCode.KEY_DOWN: //DOWN arrow
navigation("DOWN");
break;
case TvKeyCode.KEY_ENTER: //OK button
go_to(current_item);
console.log("ENTER Button");
break;
default:
console.log("Key code : " + e.keyCode);
break;
}
});
};
function tester(){
console.log("TESTTTTTTT");
};
function navigation(direction){
$("#btn_"+current_item).removeClass("selected_btn");
if(direction == "UP"){
if(current_item == 1)
current_item = total_item;
else
current_item--;
}else if(direction == "DOWN"){
if(current_item == total_item)
current_item = 1;
else
current_item++;
}
$("#btn_"+current_item).addClass("selected_btn");
};
function go_to(current_item){
sessionStorage.setItem("key", current_item);
if(current_item==2)
parent.location="about.html";
if(current_item==1){
console.log("redirection");
parent.location="menu.html";
}
};
function fetchingFirstPageAsync(){
var startTime = (new Date()).getMilliseconds();
var c = Backendless.Persistence.of("CategoriesObject").find();
console.log("============ Fetching first page using the SYNC API ============");
console.log( "Loaded " + c.data.length + "restaurant objects" );
console.log( "Total restaurants in the Backendless storage - " + c.totalObjects);
for(var i = 0; i < c.data.length; i++) {
categories.push(new Category(c.data[i].name+"",c.data[i].iconName+"",c.data[i].score+"",c.data[i].category+""));
console.log(c.data[i].category) ;
}
for (var i in categories) {
console.log(categories[i].getName());
}
console.log("Total time (ms) - " + ((new Date()).getMilliseconds() - startTime ));
};
According to the document, currently the WebSQL is supported in mobile application only.
I tried it in Wearable Gear but it didn't work. It worked in mobile.
main.js
var db;
//database version setting
var version = 1.0;
//database name setting
var dbName = "tizendb";
//database display name setting
var dbDisplayName = "tizen_test_db";
//database size setting
var dbSize = 2 * 1024 * 1024;
function selectDB() {
if (window.openDatabase) {
//openDatabase(name, version, displayname, estimatedsize, callback);
db = openDatabase(dbName, version, dbDisplayName, dbSize);
dropTable(db);
createTable(db);
//inserting data in table
insertData(db, "tizenTest01", "We are pleased to announce that Tizen 2.0");
insertData(db, "tizenTest02", "device vendors. We encourage you to download");
insertData(db, "tizenTest03", "installed and used it. If you have questions");
insertData(db, "tizenTest04", "This release includes many new features");
insertData(db, "tizenTest05", "Highlights of this release include");
dataView(db);
} else {
alert("Web SQL Database is not supported in this browser");
}
}
//reads and displays values from the 'places' table
function dataView(db) {
var html = document.getElementById("tbody01");
var ddlHtml = document.getElementById("ddlTitle");
html.innerHTML = "";
ddlHtml.innerHTML = "";
db.transaction(function (t) {
t.executeSql("SELECT * FROM tizenTable", [],
function (tran, r) {
ddlHtml.innerHTML = "<option value='all'>all</option>";
for (var i = 0; i < r.rows.length; i++) {
var id = r.rows.item(i).id;
var title = r.rows.item(i).title;
var content = r.rows.item(i).content;
var insertday = r.rows.item(i).insertDay;
//data list rendering
if (html) {
html.innerHTML += "<tr><td>" + id + "</td><td>" + title + "</td><td>" + content + "</td><td>" + insertday + "</td></tr>";
}
//select box rendering
if (ddlHtml) {
ddlHtml.innerHTML += "<option value=" + id + ">" + title + "</option>";
}
}
},
function (t, e) { alert("Error:" + e.message); }
);
});
}
// create table
function createTable(db) {
db.transaction(function (t) {
t.executeSql("CREATE TABLE tizenTable (id INTEGER PRIMARY KEY, title TEXT, content TEXT, insertDay DATETIME)", []);
});
}
//inserting data in table
function insertData(db, title, context) {
db.transaction(function (e) {
var day = new Date();
e.executeSql("INSERT INTO tizenTable(title, content, insertDay) VALUES (?, ?, ?)", [title, context, day], onSuccess, onError);
});
}
function onSuccess(e) { }
function onError(e) { }
// drop table
function dropTable(db) {
db.transaction(function (e) {
e.executeSql("DROP TABLE tizenTable");
});
}
//Select the data conditions
function dataChange(value) {
if (value != "all") {
var html = document.getElementById("tbody01");
html.innerHTML = "";
db.transaction(function (t) {
t.executeSql("SELECT * FROM tizenTable WHERE id=?", [value],
function (tran, r) {
for (var i = 0; i < r.rows.length; i++) {
var id = r.rows.item(i).id;
var title = r.rows.item(i).title;
var content = r.rows.item(i).content;
var insertday = r.rows.item(i).insertDay;
if (html) {
html.innerHTML += "<tr><td>" + id + "</td><td>" + title + "</td><td>" + content + "</td><td>" + insertday + "</td></tr>";
}
}
},
function (t, e) { alert("Error:" + e.message); }
);
});
} else {
dataView(db);
}
}
window.onload = function () {
selectDB();
};
Index.html
<thead>
<tr>
<th>id</th>
<th>title</th>
<th>context</th>
<th>date</th>
</tr>
</thead>
<tbody id="tbody01">
</tbody>

Categories

Resources