Handlebars display AJAX JSON response - handlebars.js

I am new to handlebars.js and I am trying to display a JSON response with this API https://yts.am/api/v2/list_movies.json
I try to use static and basic JSON data, it is working but when I try to load huge amount I get error
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1 id="title"></h1>
<hr>
<div id="result"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
<script id="text-template-yts" type="text/x-handlebars-template">
<h2>{{title}}</h2>
<h3>{{summary}}</h3>
<ul>
{{#each torrents}}
<li>{{quality}}</li>
{{/each}}
</ul>
</script>
<script>
function ajax_get(url, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('responseText:' + xmlhttp.responseText);
try {
var data = JSON.parse(xmlhttp.responseText);
} catch (err) {
console.log(err.message + " in " + xmlhttp.responseText);
return;
}
callback(data);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
ajax_get('https://yts.am/api/v2/list_movies.json', function (data) {
document.getElementById("title").innerHTML = data["status_message"];
var source = document.getElementById('text-template-yts').innerHTML;
var template = Handlebars.compile(source);
var html = template(data.data.movies);
document.getElementById("result").innerHTML = html;
});
</script>
</body>
</html>
I was able to get the query success but in parsing is error

FIXED
I need to add the each of handlebars

Related

pug file, to connect to Websocket, and then display values arriving?

Here's a simple pug file
p Hello
The backend is ordinary node, express, passport, sql so something like
app.get('/example', (request, response) => {
response.render('example.pug');
})
I want the web page to
Connect to a websocket server
Any text that arrives, simply display that where the 'Hello' is
How to do this?
(So, TBC the server looks something like this ... I can easily do that end of it.)
function sendInfoToAnyBrowserConnected() {
connections.forEach(function tell(c) {
if (c.readyState == WebSocket.OPEN) {
c.send("this text gets displayed")
What should I put in my pug file?
I've had to figure it out myself - damn you, SO! Essentially this
<a id="log" size=10></a>
with this
var el = document.getElementById("log");
and this
el.innerHTML = el.innerHTML + "<br>" + e.data;
and that's it.
So in total basically
<html>
<head>
<script type="text/javascript">
function VanillaData() {
var ws = new WebSocket("ws://ws.yours.com:2345");
ws.onopen = function() { ws.send("from www ,v1"); };
ws.onmessage = function(e) {
el.innerHTML = el.innerHTML + "<br>" + e.data;
};
ws.onclose = function() { console.log("ws closed..."); };
}
</script>
</head>
<body>
Your live stuff:
<br>
<a id="log" size=10></a>
<script type="text/javascript">
var el = document.getElementById("log");
VanillaData()
</script>
</body >
</html >
I'm not knowledgeable about pug, so cannot comment on how the .pug file should look.
Using an online html-pug convertor, this does work:
head
script(type='text/javascript').
function VanillaData() {
var ws = new WebSocket("ws://you.com:2345");
ws.onopen = function() { ws.send("from www"); };
ws.onmessage = function(e) {
el.innerHTML = e.data + "<br>" + el.innerHTML;
};
ws.onclose = function() { console.log("ws closed ..."); };
}
| Live stuff:
br
pre#log(size='10').
script(type='text/javascript').
var el = document.getElementById("log");
VanillaData()
Seems to work great.

How import file Excel to multiple tables in DB using asp.net and angularJS?

I have developed an application, and in this application I want to import file Excel to multiple table in my DB, and since i am a beginner in angularJS and .NET, I work with .net web api and angularjs, and I develop a function, it works when I import the data into a singe table, but the problem how to import the data into 3 table in DB !!! . and the 3 tables are linked to each other (in my exemple code there 2 table Candidature and Candidat). My question is: how to import Excel file to multiple table in DB and thank's. ( i work with asp.net web API and angularJS )
controller.cs:
/////
[Route("api/Candidature/SaveData")]
[HttpPost]
[ResponseType(typeof(Candidat))]
public IHttpActionResult SaveData(List<Candidature> Candidatures, List<Candidat> candidat)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
foreach (var data in Candidatures)
{
db.Candidature.Add(data);
}
db.SaveChanges();
foreach (var data in candidat)
{
db.Candidat.Add(data);
}
db.SaveChanges();
return StatusCode(HttpStatusCode.OK);
////
service.js:
SaveData: {
method: 'POST' ,
url: serviceBase + 'Candidature/SaveData',
isArray: true,
headers: {
'Content-Type' : 'application/json'
}
},
CandidatureCtrl.js :
$scope.Importation = function (data) {
$scope.SelectedFileForUpload = null;
$scope.UploadFile = function (files) {
$scope.$apply(function () { //I have used $scope.$apply because I will call this function from File input type control which is not supported 2 way binding
$scope.Message = "";
$scope.SelectedFileForUpload = files[0];
})
};
//Parse Excel Data
$scope.ParseExcelDataAndSave = function () {
var file = $scope.SelectedFileForUpload;
if (file) {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
//XLSX from js-xlsx library , which I will add in page view page
var workbook = XLSX.read(e.target.result, { type: 'binary', cellDates:true, cellStyles:true });
var sheetName = workbook.SheetNames[0];
var excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
if (excelData.length > 0) {
//Save data
Candidature.SaveData(excelData).then(function (data) {
if (data.status) {
$scope.Message = excelData.length + " record inserted";
}
else {
$scope.Message = "Failed";
}
}, function (error) {
$scope.Message = "Error";
});
// Candidature.SaveDatacandidature(excelData).then(function (data) {
// if (data.status) {
// $scope.Message = excelData.length + " record inserted";
// }
// else {
// $scope.Message = "Failed";
// }
// }, function (error) {
// $scope.Message = "Error";
// });
// $scope.SaveData(excelData);
}
else {
$scope.Message = "No data found";
}
}
reader.onerror = function (ex) {
console.log(ex);
}
reader.readAsBinaryString(file);
}
};
var dialogOpts = {
backdrop: 'static',
keyboard: false,
scope: $scope,
size: 'lg',
templateUrl: 'views/candidature/Importation.html',
controller: ['$scope', '$uibModalInstance','$sce',
function ($scope, $uibModalInstance, $sce) {
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
}
]
};
$uibModal.open(dialogOpts);
};
Importation.html :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.1/xlsx.full.min.js"></script>
<script src="http://oss.sheetjs.com/js-xlsx/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<!--<script src="app/views/candidature/candidatureCtrl.js"></script>-->
</head>
<body ng-app="agu">
<div ng-controller="candidatureCtrl" class="container" style="margin-top:50px;">
<div class="form-inline">
<input type="file" name="file" class="form-control"
onchange="angular.element(this).scope().UploadFile(this.files)"/>
<input type="button" value="Import" class="btn btn-success" ng-disabled="!SelectedFileForUpload"
ng-click="ParseExcelDataAndSave()" />
<br/>
<span style="color:red">
{{Message}}
</span>
</div>
</div>
</body>
</html>
In your web api, you are expecting two arrays for Candidatures and candidat.
But from your controller you are passing only one array of data excelData.
So when it comes to api it doesn't execute this code,
foreach (var data in candidat)
{
db.Candidat.Add(data);
}
Because candidat is either null or undefined. So it can't go through the loop which the below code is never executed.
db.Candidat.Add(data);

How to implement websockets in Progress OpenEdge?

I'm trying to implement a websocket-server with Progress OpenEdge. I still didn't get it working.
I've successfully created a socket-server with the example i-sktsv1.p from here.
When I run my html-page, which looks like:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<title>WebSocket Client</title>
<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:3333/";
var output;
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
// websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt) {
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
function onMessage(evt) {
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
websocket.close();
}
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<body>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
I getting a error that the websocket connection could not be established.
The problem is (I think) that Progress offers a socket, not a websocket. Do you know how to get this working?

Pure javascript ajax call asp.net webmethod

I would not like to call asp.net server side code with jquery $.ajax .
So I have written a pure javascript ajax file .But when I call webmethod,this do not work.
Can anyony help me out how correct this? THANK you very much .
ajax.js:
var ajax = {
_params: null,
_callback: null,
_xhr: null,
_createXHR: function () {
if (window.ActiveXObject) {
_xhr = new ActiveXObject("Microsoft.XMLHTTP"); //IE
}
else if (window.XMLHttpRequest) {
_xhr = new XMLHttpRequest(); //FireFox,Chrome et.
}
},
_ajaxcallback: function () {
if (_xhr.readyState == 4) {
if (_xhr.status == 200) {
_callback.call(this, _xhr.responseText)
}
}
},
_changeParams: function () {
var args = arguments[0];
var s = "";
for (var i in args) {
s += "&" + i + "=" + args[i];
}
_params = s;
},
get: function (url, params, callback) {
_callback = callback;
ajax._createXHR();
ajax._changeParams(params);
if (null != _xhr) {
_xhr.open('get', url + '?' + _params, true);
_xhr.onreadystatechange = ajax._ajaxcallback;
_xhr.send();
}
},
post: function (url, params, callback) {
_callback = callback;
ajax._createXHR();
ajax._changeParams(params);
if (null != _xhr) {
_xhr.open('post', url, true);
_xhr.onreadystatechange = ajax._ajaxcallback;
_xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
_xhr.send(_params);
}
}
}
WebForm1.aspx
<head runat="server">
<title></title>
<script src="ajax.js" type="text/javascript"></script>
<script type="text/javascript">
function ajaxtest() {
var uid = document.getElementById("txtuid").value;
var pwd = document.getElementById("txtpwd").value;
ajax.post("WebForm1.aspx/GetModel", "{ 'uid':" + uid + ", 'pwd':" + pwd + " }", function (data) {
alert(data);
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txtuid" value="eeee" />
<input type="text" value="222" id="txtpwd" onblur="ajaxtest()"/>
WebForm1.cs:
[WebMethod]
public static string GetModel(string uid,string pwd)
{
return "1";
}
In your markup you need to have a ScriptManager with EnablePageMethods set to true. Doing this will ensure you can call the methods you have marked up with [WebMethod].
In your JavaScript you can then call your method like this: PageMethods.GetModel("userName", "password", OnSuccessMethod, OnFailureMethod); - you won't need any of the ActiveXObject/XmlHttpRequest stuff if you do it this way, which keeps things much simpler.
Use AJAX.PRO from Michael Schwarz --> http://www.ajaxpro.info/

Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

I am trying to get nowelium / socket.io-titanium to work i have it working on the device but on website i get the following error in my console
XMLHttpRequest cannot load http://127.0.0.1:8080/socket.io/1/?t=1345807417891. Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.
I am using socket.io here is the chat.js server
var io = require('socket.io').listen(8080);
var archiveMessages = {};
var channels = ['foo channel', 'bar channel'];
var chat = io.of('/chat');
chat.on('connection', function(socket){
console.log('connected: %s', socket.id);
// push available channel list
socket.emit('available_channel', channels);
socket.on('join', function(value){
console.log('%s joined channel: %s', socket.id, value.channelId);
socket.join(value.channelId);
socket.set('channel_id', value.channelId, function(){
var messages = archiveMessages[value.channelId] || [];
socket.emit('joined', messages);
socket.broadcast.to(value.channelId).emit('user:join', {
id: socket.id
});
});
});
socket.on('post', function(message){
socket.get('channel_id', function(err, channelId){
console.log('%s says<%s channel>: %s', socket.id, channelId, message);
if(!(channelId in archiveMessages)){
archiveMessages[channelId] = [];
}
archiveMessages[channelId].push(message);
socket.emit('posted', {
message: message
});
socket.broadcast.to(channelId).emit('user:message', {
id: socket.id,
message: message
});
});
});
socket.on('disconnect', function(){
console.log('%s disconnected', socket.id);
socket.get('channel_id', function(channelId){
socket.leave(channelId);
socket.broadcast.to(channelId).emit('user:leave', {
id: socket.id
});
});
});
});
var image = io.of('/image');
image.on('connection', function(socket){
socket.on('upload', function(param){
console.log('upload base64 size: %d', param.base64.length);
if(param.download){
socket.emit('download', {
base64: 's' + new Array(65534).join('0') + 'e'
});
}
});
});
and here is the index.html i am running
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="height=device-height, width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>chat sample</title>
<style>
#rooms button {
display: block;
}
</style>
<script type="text/javascript" src="http://localhost:8080/socket.io/dist/socket.io.js"></script>
<script type="text/javascript">
var $ = function(id){
return document.getElementById(id);
};
window.addEventListener('load', function (){
var socket = io.connect('127.0.0.1:8080');
var chat = socket.of('/chat');
console.log(chat);
chat.on('available_channel', function(channels){
channels.forEach(function (channelId){
var button = document.createElement('button');
button.appendChild(document.createTextNode(channelId));
$('rooms').appendChild(button);
button.addEventListener('click', function(){
$('chat').style.display = '';
chat.emit('join', {
channelId: channelId
});
});
});
});
var addMessage = function(message){
var li = document.createElement('li');
li.appendChild(document.createTextNode(message));
$('messages').appendChild(li);
};
chat.on('joined', function(messages){
messages.forEach(function(message){
var li = document.createElement('li');
li.appendChild(document.createTextNode(message));
$('archives').appendChild(li);
});
});
chat.on('posted', function(value){
return addMessage('you posted: ' + value.message);
});
chat.on('user:join', function(value){
return addMessage(value.id + ' joined this channel');
});
chat.on('user:leave', function(value){
return addMessage(value.id + ' leaved this channel');
});
chat.on('user:message', function(value){
return addMessage(value.id + ' says ' + value.message);
});
$('submit').addEventListener('click', function (){
var messageValue = $('message').value;
if(/^\s+$/.test(messageValue)){
return;
}
chat.emit('post', messageValue);
$('message').value = '';
});
});
</script>
</head>
<body>
<div id="rooms">
</div>
<div id="chat" style="display:none">
<input type="text" id="message" value="" placeholder="message here" />
<input type="submit" id="submit" value="send" />
<p>archives</p>
<ul id="archives" style="color: #999"></ul>
<p>messages</p>
<ul id="messages"></ul>
</div>
</body>
</html>
CAn anyone tell me why this might be happening???
I wonder if switching it to localhost would fix that.
I researched into Access-Control-Allow-Origin and traced it to the web browser as the culprit if I remember correctly. I eventually started looking for a way to disable the browser from checking for that. In Chrome this is my shortcut path.
...Chrome\Application\chrome.exe --allow-file-access-from-files --disable-web-security
See if that works. I don't know if it really remedies the issue as much as it just suppresses the problem. If you were calling the web page from the host you were trying to access I don't think you'd have this problem at all. For example, when I attempt to access my web service on mydomain.com using the web page mydomain.com/myprogram.html it doesn't complain about cross domain access.

Resources