sailsJs - data passed from controller is not available in view - sails.js

I've been struggling with this issue for hours and I can't find a solution to it, I can also not find a solution on internet, i've been reading over and over again the docs and I am doing it as displayed as I can tell, but it won't work.
I am trying to pass an array from the controller to the view and it's just not working, I get the error that the variable is undefined even if I use an if statement, and even if I use locals.errors (errors is my array sent from controller), it still won't display any data.
controller
/**
* AuthControllerController
*
* #description :: Server-side actions for handling incoming requests.
* #help :: See https://sailsjs.com/docs/concepts/actions
*/
module.exports = {
login: async function (req, res) {
},
signup: async function (req, res) {
let username = req.param('username'),//regex condition should be added to model
password = req.param('password'),
confirmedpass = req.param('confirmedpass'),
email = req.param('useremail');
let errors = [];
if (password !== confirmedpass) {
errors.push('Passwords doesn\'t match');
}
if (!_.isString(username) || username.length > 20 || !username.match(/^[a-zA-Z0-9]+$/)) {
errors.push('Username must not be longer as 20 characters, letters and numbers only');
}
if (await Account.findOne({username: username})) {
errors.push('Username already exists');
}
if (await Account.findOne({email: email})) {
errors.push('Email is already in use');
}
if (errors.length > 0) {
console.log(`Errors ${errors}`);
return res.view('pages/signup', {errors: errors, layout: 'layouts/blanklayout'});
}
try {
await Account.create({username: username, password: password, email: email});
}
catch(e) {
return console.log(e.message);
}
return console.log(`Username: ${username} | Password: ${password} | Email: ${email}`);
},
logout: async function (req, res) {
},
loadView: function (req, res) {
return res.view('pages/signup', {layout: 'layouts/blanklayout'});
}
};
and here is the view layout
<!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">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/images/favicon.ico">
<title>LC-RP - Dashboard</title>
<link rel="stylesheet" href="/styles/vendors_css.css">
<link rel="stylesheet" href="/styles/style.css">
<link rel="stylesheet" href="/styles/skin_color.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
</head>
<body class="hold-transition theme-primary bg-img" style="background:
radial-gradient(circle at 100% 50%, transparent 20%, rgba(255,255,255,.2) 21%, rgba(255,255,255,.2) 34%, transparent 35%, transparent),
radial-gradient(circle at 0% 50%, transparent 20%, rgba(255,255,255,.2) 21%, rgba(255,255,255,.2) 34%, transparent 35%, transparent) 0 -50px;
background-color: rgb(154, 160, 165);
background-size:75px 100px;" data-overlay="5">
<%- body %>
<script src="/js/vendors.min.js"></script>
<script src="/dependencies/assets/icons/feather-icons/feather.min.js"></script>
<script src="/js/pages/toastr.js"></script>
<% if ( errors ) { %>
<script>
$(function() {
let testVar = "<%- errors %>";
console.log(`test, ${locals}`);
})
</script>
<% } %>
</body>
</html>
You can see that I try to display the errors at the bottom of the view layout code in a script tag.
This is in the layout, but even if I do it in the view itself, it won't work, errors doesn't display any data, it doesn't even exist.

It seems like you are sending a response only here: if (errors.length > 0). So you can move your return res.view() after the try-catch in the finally block:
try {
await Account.create({username: username, password: password, email: email});
}
catch(e) {
errors.push(e.message);
} finally {
return res.view('pages/signup', {errors: errors, layout: 'layouts/blanklayout'});
}
Or in the layout include if (typeof errors === ‘undefined’ {var errors = []}

The controller has to return to the assets/js/pages/auth.page.js (a wrapper for the Vue2+) which in turn provide the vars for the views/pages/auth.ejs.

Related

How to read full DOM source including frames in Electron?

I can't figure out how to get access to the full source of the HTML page including iframes. It should be similar to what we see in DevTools > Elements, but via Electron.
By source I mean either text representation of the DOM (including content of all iframes on the page), or the list of all elements and having a way to get access to their text-representations.
Any help is highly appreciated! Thanks.
If you're just looking to get a string of all the HTML, you can do so via the executeJavaScript API:
const {app, BrowserWindow, dialog} = require('electron')
async function createWindow () {
const mainWindow = new BrowserWindow()
await mainWindow.loadFile('index.html')
const result = await mainWindow.webContents.executeJavaScript("document.documentElement.outerHTML");
dialog.showMessageBox(mainWindow, {
message: result
});
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
For an HTML page like:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="./styles.css" rel="stylesheet">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
<iframe src="https://google.com/chrome"></iframe>
</body>
</html>
You'll get a dialog like this:
It is not however possible to just grab DOM elements in the main process that you can manipulate.

ionic video capture and display

controller.js
var app = angular.module('startervideo', ['ionic','ngCordova'])
app.controller('VideoCtrl', function($scope,$cordovaCapture) {
$scope.data = {
videoPath: ""
};
$scope.captureVideo = $scope.captureVideo = function() {
var options = {duration: 15 };
$cordovaCapture.captureVideo(options).then(
function(videoData) {
// Success! Video data is here
$scope.data.videoPath = "file:/" + videoData[0].fullPath;
console.log(videoData);
}, function(err) {
// An error occurred. Show a message to the user
console.log(err);
});
}
});
app.js
var app = angular.module('starter', ['ionic','ngCordova','startervideo'])
app.directive("cordovaVideo", function () {
return {
restrict: 'AEC',
scope: {src: '='},
link: function(scope, element, attrs) {
scope.$watch('src', function(newVal, oldVal) {
if (scope.src != "") {
// Create a div object
var div = document.createElement('div');
div.innerHTML = "<video id=\"myCordovaVideo\"controls>"+
"<source src=\"" + scope.src + "\" type=\"video/quicktime\">"+ "</video>";
// Delete previous video if exists
var previousDiv = document.getElementById('myCordovaVideo');
if (previousDiv)
previousDiv.remove();
// Append new <video> tag into the DOM
element.append(div);
}
}); }
} });
#myCordovaVideo {
background: red;
width: 100%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link rel="manifest" href="manifest.json">
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controller.js"></script>
</head>
<body ng-app="starter" ng-controller="VideoCtrl">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">VideoPro</h1>
</ion-header-bar>
<ion-content>
<button class="button button-calm button-full"
ng-click="captureVideo()">Capture Video</button>
<cordova-video src="data.videoPath"></cordova-video>
</ion-content>
</ion-pane>
</body>
</html>
Hi everyone I am new in ionic1 framework been trying to develop an application that can capture video display them on the UI and ultimately store in a remote serve, so far the code that I have can capture video but it does not display it on the UI.The example that I am following comes from ionic cookbook I am in desperate need of help here is the code that I have
I've created a similar Ionic app that captures video and uploads it to a remote server. You may find it useful
https://github.com/aliasav/ionic-video

getJSON - Loading Image Gallery From Public Server - Flickr

I have tried so many URL variations for Flickr and all attempts have failed to load my image gallery into my own webpage.
I am pretty sure its the URL. If I replace the URL with:
"api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"
all works fine to load public photos from Flickr, but to load my own album (URL below), it won't work.
Yes I have a valid API from Flickr. I also checked the script syntax in "jsbin.com" and all of that is good.
Can anyone help resolve this?
Here is the jQuery script:
(function() {
var flickerUrl = "https://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=<removed by edit>&user_id=135938131#N02&format=json&jsoncallback=?";
$.getJSON(flickerUrl)
.done(function(data) {
$.each(data.items, function(i, item) {
var image = $("<img>")
.attr("src", item.media.m)
.attr("title", item.title);
$("<a>")
.attr("href", item.link)
.attr("target", "_blank")
.html(image)
.appendTo("#images");
if ( i === 8 ) {
return false;
}
});
});
})
();
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Flickr Image Gallery</title>
<link rel="stylesheet" href="css/main.css" />
</head>
<body>
<h1>Natural Scenery</h1>
<br>
<div id="images"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="./js/flickrgallery.js"></script>
</body>
</html>

Is it possible to highlight a search pattern when codemirror loads

Is there a way for codemirror to highlight the code matching a pattern (like if I use the search addon) when the page load? So I could load the page with ?search=my_pattern and pass the pattern to codemirror.
Here's a sample code and a jsfiddle. You can use CTRL+F to use the search addon.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/codemirror.css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/codemirror.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/search.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/searchcursor.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/match-highlighter.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/python.js"></script>
</head>
<body>
<textarea id="myTextArea">print "hello world"</textarea>
<script>
var myTextArea = document.getElementById('myTextArea');
var myCodeMirror = CodeMirror.fromTextArea(myTextArea, {
'mode': 'python',
'lineNumbers': true
});
</script>
</body>
</html>
http://jsfiddle.net/ErxMb/
I figured out how to do it using overlay.js by looking at the CodeMirror: Overlay Parser Demo.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/codemirror.css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/codemirror.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/search.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/searchcursor.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/overlay.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/match-highlighter.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/python.js"></script>
</head>
<style type="text/css">
.cm-highlightSearch {background: yellow;}
</style>
<body>
<textarea id="myTextArea">print "hello world"</textarea>
<script>
var keyword = 'hello';
CodeMirror.defineMode("highlightSearch", function(config, parserConfig) {
var searchOverlay = {
token: function(stream, state) {
if (stream.match(keyword)) {
return "highlightSearch";
}
while (stream.next() != null && !stream.match(keyword, false)) {}
return null;
}
};
return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "python"), searchOverlay);
});
var myTextArea = document.getElementById('myTextArea');
var myCodeMirror = CodeMirror.fromTextArea(myTextArea, {
'mode': 'highlightSearch',
'lineNumbers': true
});
</script>
</body>
</html>
http://jsfiddle.net/HkjY7/

iphone phone gap application using javascript

In my iPhone phonegap application I want to capture image using camera of device.I have done with the following code but it not works.Am not able to capture image.
In the following code in HTML section i have one button and when it clicked then i will call method defined of java script.
<script type="text/javascript" charset="utf-8" src="phonegap.0.9.4.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for PhoneGap to connect with the device
function onLoad() {
document.addEventListener("deviceready",onDeviceReady,false);
}
// PhoneGap is ready to be used!
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved (taken with camera)
function onPhotoDataSuccess(imageData) {
alert("Your photo was taken successfully.");
}
// Called when a photo is successfully retrieved (out of the device's library)
function onPhotoURISuccess(imageURI) {
// Get image handle
var largeImage = document.getElementById('largeImage');
// Unhide image elements
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
largeImage.src = imageURI;
var options = new FileUploadOptions();
options.fileKey="file";
//options.fileName="newfile.txt";
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "http://www.yourdomain.com/upload.php", win, fail, options);
// Make sure you use your own site!
}
// Success reporting
function win(r) {
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
}
// Error reporting
function fail(message) {
alert('Failed because: ' + message);
}
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, fail, { quality: 30 });
}
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, fail, {
quality: 30,
destinationType: destinationType.FILE_URI,
sourceType: source
});
}
</script>
</head>
<body onload="onLoad()">
<button onclick="capturePhoto();">Take a Photo</button>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Upload a Photo</button>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
will you please try with the following snippet.
It capture the image from camera and also load in img tag. I tested on device.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Change this if you want to allow scaling -->
<meta name="viewport" content="width=default-width; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PGCamera</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
/* When this function is called, PhoneGap has been initialized and is ready to roll */
function onDeviceReady()
{
// do your thing!
}
function PictureSourceType() {};
PictureSourceType.PHOTO_LIBRARY = 0;
PictureSourceType.CAMERA = 1;
function getPicture(sourceType){
var options = { quality: 10 };
if (sourceType != undefined) {
options["sourceType"] = sourceType;
}
// if no sourceType specified, the default is CAMERA
navigator.camera.getPicture(getPicture_Success, null, options);
};
function getPicture_Success(imageData){
alert("getpic success");
document.getElementById("test_img").src = "data:image/jpeg;base64," + imageData;
}
</script>
</head>
<body onload="onBodyLoad()">
<img style="width:60px;height:60px" id="test_img" src="" />
<!-- for testing, add the buttons below -->
<button onclick="getPicture()">From Camera</button>
<button onclick="getPicture(PictureSourceType.PHOTO_LIBRARY)">From Photo Library</button>
</body>
</html>
thanks,
Mayur