Uploadify Script is not working when inside kohana controller - kohana

Hello I am trying to implement the uploadify script in kohana 2.3.4, it works when i place the uploadify script on the root directory then point it out on my view file. But when I point the script to a controllr, it returns a http error. Below is the js script:
<script type="text/javascript">
// <![CDATA[
$(document).ready(function() {
$('#file_upload').uploadify({
'uploader' : '<?=url::base()?>uploadify/uploadify.swf',
'script' : '<?=url::base()?>uploadify', /*Even tried http://localhost/directory/uploadify*/
'cancelImg' : '<?=url::base()?>uploadify/cancel.png',
'folder' : '<?=url::base().$directory?>',
'multi' : true,
'removeCompleted' : false,
'auto' : true
});
});
// ]]>
</script>

Not sure what error you were receiving but if your page requires authentication and controller not able to authenticate user then you can follow my solution.
Problem is that uploadify uses flash and there is bug in flash that it does not sent cookies to server.
I changed it at shown below to get it working.
in js (for kohana)
$('#file_upload').uploadify({
uploader: base_url+"upload/image?sess=<?php Session::instance()->id(); ?>",
});
and in plain php
$('#file_upload').uploadify({
uploader: base_url+"upload/image?sess=<?php session_id();?>",
});
and in kohana controller while reading authentication from session, initialize session as following
$sess_id = Arr::get($_GET,'sess',null);
$sess = Session::instance(null,$sess_id);
or in plain php
session_name($_GET['sess']);
session_start();
in future if bug in flash is fixed then there will be no need to do this

Related

How do I get a Electron app object through HTML (script tag)?

So I have here this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Oh no!</title>
</head>
<body>
<label>Oh dear. A serious error occurred and the app needs to restart. Press the button below to restart.</label>
<br>
<button onclick="restart()">Restart</button>
<script>
const { app } = require("electron")
function restart() {
app.relaunch()
app.exit()
}
</script>
</body>
</html>
And now, when the app receives an unhandled error this will show... but when the user clicks the button, the app doesn't restart so how would I make the app restart?
You can't get the app object without using preload.js and neither is directly getting the app object safe. There is a method to do the above using preload.js and ipcRenderer which are pure Electon APIs
In electron (even in web development), there is server-side code and browser-side code. The code written in between the script tags in your snippet is server side code which will fail to execute in browser side.
Server-side code in your case is in NodeJS Backend and browser-side code is the one which is the HTML Page and its own javascript.
So to close the window (which only NodeJS can do, i.e., the backend) you need to use Electron's ipcRenderer which helps string based communication between the browser-side javascript and the server-side javascript.
While creating a browser window in electron using new BrowserWindow(options) where options is an object. Define the object as:
options = {
webPreferences: {
preload: preload.js, //You need to create a file named preload.js (or any name) in your code
nodeIntegration: true,
contextIsolation: false,
}
}
Now in a new file called preload.js:
window.ipcRenderer = require('electron').ipcRenderer;
In your snippet you added const { app } ... which should be done this way to inject the javascript using a preload property in the object.
Now in the main app.js file (whatever you named maybe index.js) where you created the browser window:
const ipc = require('electron').ipcMain; //Add to your pre-existing code
ipc.on("close-app", (event, message) => { //"close-app" can be anything but, you need to use the same key in the send message side (later in this answer)
browserWindow.close(); //If you named the browserwindow as browserWindow
});
Now in your HTML (i.e., send message side)
...
<script>
window.ipcRenderer("close-app", ""); //Second parameter is used if you want to send some extra message. The extra message can be viewed in the server side from the message parameter in the app.js code (just above this paragraph)
</script>
This is a bit difficult if you are doing it for the first time.
I've added more articles which will help you clear your confusions:
Highlight about server-side and browser-side code
Relation with socket.io communication in NodeJS

Ui router Couldn't find views with Nodejs

I'm working on nodejs application we use the Ui router to implement single page application , I Created the controller in node js that load the Layout which have angular scripts and libraries , and then I tried to navigate throught the routes I defined in ui router , each time I got the error in the console said "angular.js:8081 GET http://localhost:2405/Views/Partials/Know-me.html 404 (Not Found)"
I can't specify the problem
this is some code :
Nodejs Controller
app.get("/",function(req , res){
res.render("Template.ejs"); // this is the layout
});
Layout Scripts :
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="../../angular_js/app_angular.js"></script>
and the app_angular script :
var appmodule = angular.module('mainApp',[ui.router]);
appmodule.config(function($stateProvider , $urlRouterProvider , $locationProvider){
$urlRouterProvider.otherwise('/things');
$stateProvider
.state('me',{
url : '/me',
templateUrl : '/Views/Partials/Know-me.html'
})
.state('amir',{
url : '/amir',
templateUrl : '/Know-me-amir.html'
});
//$locationProvider.html5Mode(true);
});
structure of the project :
-- View
--- Shared
---- Temaplte.ejs
--- Partials
---- know-me.html
-- Scripts
--- angular_js
---- angular_app.js
The problem is:
ejs files are rendered on the server. AngularJS (client) tries to fetch
'Views/Partials/Know-me.html'. From client's perspective this html does not exist.
Please do the following:
Add an public folder.
Serve the public folder with express.static()
Move the html files to this directory: public/Views/Partials/Know-me.html
Try to access http://localhost:2405/Views/Partials/Know-me.html - if you see the contents of know-me - your are good to go!
now your client will find the asyncronisly loaded html file.

Angular and Sails routing configuration

Is there any Sails.js (or Node) configuration which can prevent Angular routing from working?
No matter what approach I take, every rout apart from ones in sails' routes.js return 404.
I've tried both 1.2 and 1.3 Angular versions, and I'm using Sails v 0.9.15.
All scripts are loaded in correct order (for example):
<script src="/linker/js/libs/angular/angular.js"></script>
<script src="/linker/js/libs/angular/angular-resource.js"></script>
<script src="/linker/js/libs/angular/angular-route.js"></script>
<script src="/linker/js/libs/angular/angular-sanitize.js"></script>
...
<script src="/linker/js/app.js"></script>
I'm using the ngRoute correctly:
var myApp= angular.module('myApp', ['ngRoute']);
Here are my routes in Angular's app.js:
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/profile',
{ templateUrl: 'linker/views/profile.html', controller: 'MainCtrl' })
.when('/profile-detail',
{ templateUrl: 'linker/views/profile_detail.html', controller: 'MainCtrl' });
}]);
And I'm also using location provider:
myApp.config(function ($locationProvider) {
$locationProvider.html5Mode(true);
});
Additional details:
ng-app and ng-view are correctly placed, and my paths are correct. I can correctly show profile.html with Angular (and also to include data from Sails' Restful API).
Problem is, that I can only do that for routes defined in Sails' routes.js.
Example:
module.exports.routes = {
'/' : {
controller: 'main',
action: 'index'
},
'/signup' : {
controller: 'main',
action: 'signup'
},
'/login' : {
controller: 'main',
action: 'login'
},
'/profile': {
controller: 'users',
action: 'profile'
} //......
So basically, in order to show some html content with Angular, I have to define EXACTLY THE SAME route in Sails' configuration, which makes no sense.
Any ideas? P.S. I'll provide additional data if needed.
Try removing the html5 mode to see what happens:
$locationProvider.html5Mode(false);
If you are using your sails application only to provide an API for your Angular app, but you are using the same backend to serve your angular code, then you could prefix all API routes with 'api' in order to prevent having conflicts with angular routes.
Instead of /profile you would have /api/profile
EDIT:
I've taken a look into the Sails.js framework and made a small app to test it.
I was able to successfully have routes in angular work that were not defined by sails.
I think there is a misunderstanding of how angular routing works.
If you change the path with window.location or type the url manually, the browser will send a get request to the server. So in your case, there will be a request for /profile or /profilee and the server will look at the available routes and will throw a 404 if nothing matches.
To prevent that, you should actually change the path using angular methods. Angular uses the '#' symbol in the path to prevent the browser of sending requests to the server when the url changes. Browsers ignore changes after the '#' symbol. Or in your case, a similar effect is achieved using the html5 mode. Beware though that using html5 mode can cause troubles when users refresh the page, since then a request will be made to the server (more on how to fix that below).
So, what you should be using to change the paths with javascript is the $location service. In your angular views, you can also use normal anchor tags like, because angular parses those:
Go to profile
Since what you have is a single page application, alls views are handled by the client. All the paths beyond the root (/) are virtual paths created by angular. They usually don't exist in the server. Only the root is available. When using html5 mode that can be a problem.
A way to fix that is to rewrite the routing of the server to serve everything else as if it was a request to the root path. In sails they even suggest how to do that in the config/routes.js:
// What about the ever-popular "vanity URLs" aka URL slugs?
// (you might remember doing this with `mod_rewrite` in Apache)
//
// This is where you want to set up root-relative dynamic routes like:
// http://yourwebsite.com/twinkletoez
//
// NOTE:
// You'll still want to allow requests through to the static assets,
// so we need to set up this route to ignore URLs that have a trailing ".":
// (e.g. your javascript, CSS, and image files)
'get /*(^.*)': 'UserController.profile'
Regarding the API in sail, you can configure a prefix inside the config/controllers.js file:
/**
* `prefix`
*
* An optional mount path for all blueprint routes on a controller, including `rest`,
* `actions`, and `shortcuts`. This allows you to continue to use blueprints, even if you
* need to namespace your API methods.
*
* For example, `prefix: '/api/v2'` would make the following REST blueprint routes
* for a FooController:
*
* `GET /api/v2/foo/:id?`
* `POST /api/v2/foo`
* `PUT /api/v2/foo/:id`
* `DELETE /api/v2/foo/:id`
*
* By default, no prefix is used.
*/
prefix: '',

node.js jquery - .post ajax like php

I am coming from PHP where an AJAX call from jQuery is done like this.
html:
$('a').click(function(){
var mydata = 'abc123';
$.post( 'process.php', { mydata:mydata}, function(data){
$('body').append('<h1>'+data+'</h1>');
});
return false;
});
php:
$post = $_POST['mydata'];
echo $post;
Question: how can i replace the PHP part with node.js to do the same thing?
also i would need to change this part of jQuery $.post( 'process.php', ...
would that look like this? $.post( 'process.js', ...?
I saw this post but i couldnt translate it from php to node
This helped out, from "Node.js for PHP developers"
In PHP, a PHP file represents an HTML page. A web server, such as Apache, accepts
requests and if a PHP page is requested, the web server runs the PHP. But in Node.js,
the main Node.js file represents the entire web server. It does not run inside a web server
like Apache; it replaces Apache.

how to check if my javascript browser extension works

I am trying to create a simple javascript based extension for Google Chrome that takes data from one specific iframe and sends it as part of a POST request to a webpage.
The web page that sends the data submitted by POST request, to my email address.
I tried running the extension, it looks to be running fine, but I am not getting any email.
The servlet which receives form data is very simple, I dont think there is any error in it.
What I want is some way to check if the javascript based extension works or not.
The javascript code is given below-
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mypostrequest.responseText
}
else{
alert("An error has occured making the request")
}
}
}
var namevalue=encodeURIComponent("Arvind")
var descvalue=encodeURIComponent(window.frames['test_iframe'].document.body.innerHTML)
var emailvalue=encodeURIComponent("arvindikchari#yahoo.com")
var parameters="name="+namevalue+"&description="+descvalue &email="+emailvalue
mypostrequest.open("POST", "http://taurusarticlesubmitter.appspot.com/sampleform", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
mypostrequest.send(parameters)
UPDATE
I made changes so that the content in js file is invoked by background page, but even now the extension is not working.
I put the following code in background.html:
<script>
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript( null, {file: "content.js"});
});
chrome.browserAction.setBadgeBackgroundColor({color:[0, 200, 0, 100]});
</script>
Looking at your code looks like you are trying to send cross domain ajax request from a content script. This is not allowed, you can do that only from background pages and after corresponding domains are declared in the manifest. More info here.
To check if your extension works, you can open dev tools and check if there any errors in the console. Open "Network" tab and see if request was sent to your URL. Place console.log in various places in your code for debugging, or use full featured built in javascript debugger for step-by-step debugging.

Resources