AngularJS and Rest Service - rest

I've recently started experimenting with AngularJS. I am building a simple html5 application that updates a MySQL database.
[index.html]
<!DOCTYPE html>
<html ng-app="MyProject">
<head>
<title>My Project</title>
<link rel="stylesheet" href="css/main.css" type="text/css">
<script src="lib/angular-1.0.1.js"></script>
<script src="lib/angular-resource-1.0.1.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body>
<div id="main-content" ng-view>
</body>
</html>
I used the Slim framework to create a Rest Interface. My database has currently one table named location_types with two columns id and title. I have tested the Rest service in the browser so under api/locationtypes I get the following JSON:
[{"id":"1","title":"Airport"},{"id":"2","title":"Bus Station"}]
I create the service in AngularJS using the following code:
[services.js]
angular.module('myDB', ['ngResource']).
factory('LocationTypes', function($resource) {
var LocationTypes = $resource('http://localhost/project/api/locationtypes', {}, { query: {method: 'GET', isArray: true}});
return LocationTypes;
});
I also use the following code to create the app module:
[controllers.js]
angular.module('MyProject', ['myDB']).
config(function($routeProvider) {
$routeProvider.
when('/locationtypes', {controller: LocationTypesCtrl, templateUrl:'forms/locationtypes.html'}).
otherwise({redirectTo:'/locationtypes'});
});
function LocationTypesCtrl($scope, LocationTypes)
{
$scope.locationTypes = LocationTypes.query();
}
The problem is that I get no results after querying the service. The locationTypes array is of zero length when I debug. I am using the latest AngularJS release [1.0.1]. What do I miss?

Is your URL really 'http://localhost/project/api/locationtypes' or is it an external server?
If its external, then you have a CORS (cross origin) issue. Unless I'm missing something it looks correct to me.

Probably a CORS issue like Dan said.
You can bypass this by adding the following to your module config.
.config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
})
Deleting the headers set by Angular should resolve the CORS issue.
You should also add a .htaccess file in your api folder. And add this:
Header set Access-Control-Allow-Origin "*"

Related

REST not working on ColdFusion

I feel like I must be missing something obvious because the REST documentation seems so simple and the code I produced appears to work correctly unless I try to access it via REST.
hello.cfc:
component rest="true" restpath="restTest"{
remote string function sayHello() httpMethod="get"{
return "Hello World";
}
}
Service Mapping:
I have tried both default yes and no with no change.
Test Page:
<html>
<head>
<title>REST Test</title>
</head>
<body>
Calling service as an object:<br>
<cfset restTest = new hello() />
<cfdump var="#restTest.sayHello()#" />
<br>
Calling service via http:<br>
<cfhttp url="http://localhost/rest/restTest" result="restResult" method="GET" />
<cfdump var="#restResult#" />
</body>
</html>
Results:
Did you try accessing without directing the call through a connector/webserver?
Keep your project inside /cfusion/wwwroot/ and then try accessing it via browser
http://localhost:8500/rest/restTest
Sample test also worked for me after changing the URL
enter image description here
It seems like you are using a wrong URL when making HTTP request to the REST service. The URL should be like this:
http://{domain}/rest/{service mapping name}/{component level rest path}/{function level restpath}
So in your case the correct URL should be:
http://localhost/rest/api/restTest
For more info read this http://www.adobe.com/devnet/coldfusion/articles/restful-web-services.html

ERR_FILE_NOT_FOUND observed when SC.oEmbed is Called

I wonder to use SC.oEmbed to play sound from SoundCloud.But when I use it, I always get ERR_FILE_NOT_FOUND error.
I put my Source Code in Jsfiddle: http://jsfiddle.net/n2sVk/, it works OK. But when I save it to a HTML file and open it with Chrome, the error would be observed.
The Source Code is shown as below:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
</head>
<body>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<div id="wrap"></div>
<script type="text/javascript">
SC.initialize({
client_id: "c202b469a633a7a5b15c9e10b5272b78",
redirect_uri: "http://connect.soundcloud.com/examples/callback.html"
});
SC.connect(function(){
console.log("connect " + "return");
SC.get("/me", function(me){
console.log("me.username:" + me.username);
console.log("me.description:" + me.description);
SC.get("/tracks", {limit: 1}, function(tracks){
console.log("get track return");
track = tracks[0];
console.log("track.uri: " + track.uri);
console.log("track.title: " + track.title);
SC.oEmbed(track.permalink_url,
{auto_play: true},
document.getElementById("wrap"));
});
});
});
</script>
</body>
Here is the error from Chrome:
GET file://soundcloud.com/oembed.json?auto_play=true&url=http%3A%2F%2Fsoundcloud.com%2Fyung-crusty-beats%2Fmystic-juice net::ERR_FILE_NOT_FOUND sdk.js:1
oEmbed response: null
This happens because when you are testing it locally, you are on "file:///" protocol.
The library's source code is using // in place of the protocol – this lets the library work on both http and https. However, when you access your code from a file as opposed to a webserver, the oembed function will probably not work.
The solution will be to run a local web server, such as Python simple server, which you'd run from the root folder of your project:
python -m SimpleHTTPServer

publishCreate - messages not broadcasted

I stuck on publishCreate message broadcasting and have no idea what I am doing wrong.
Created a simple model called Sample:
module.exports = {
attributes: {
device: 'string',
value: 'float'
},
afterCreate: function(sample, next) {
console.log("afterCreate called");
Sample.publishCreate({value: sample.value});
console.log("publishCreate sent");
next();
}
};
Didnt find in the documentation if models do publishCreate automatically so I added afterCreate.
Then I created following view:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/styles/iphone.css">
<!-- Bring in the socket.io client -->
<script type="text/javascript" src="/js/socket.io.js"></script>
<!-- then beef it up with some convenience logic for talking to Sails.js -->
<script type="text/javascript" src="/js/sails.io.js"></script>
<!-- listen on socket.io for incoming messages -->
<script type="text/javascript" src="/js/app.js"></script>
<script type="text/javascript">
socket.on('message', function(msg){
alert('message received');
});
</script>
</head>
<body>
<div class="block" style="height: 320px;">
<div class="centered">
<h1><%= temp %>°</h1>
</div>
</div>
</body>
</html>
Theoretically now if I call the view in the browser and then in the other browser tab I call
http://localhost:1337/sample/create?device=AA&value=10.0
a message should be received on the client side in the above view but nothing happens.
I know from the messages that sockets are connected and publishCreate is called when new Sample is created.
What can be a reason? Do I also have to do something in the controller when calling res.view() ?
Did you explicitly declare your publishCreate in your create action of the controller?
'create': function(req,res,next){
Sample.create(req.params.all(), function sampleCreated(err,sample){
if(err){console.log(err); }
Sample.publishCreate({
id:sample.id,
device: sample.device,
value: sample.value
});
});
},
You should probably explicitly declare the data points that you want to publish. Here I've set the Id, device, and value to be published explicitly. Blueprints and automatic controller mapping is useful, but it might be really unstable and unreliable sometimes, especially with the lack of documentation. Better to be specific.
The likely problem here is that the controller action that contains the subscribe call is being run in response to an HTTP request, not a socket request. req.socket is meaningless when the request is via HTTP; the server has no idea what socket was used. In order for subscribe to work, the request has to be made over a socket connection, e.g. using the socket.get method in the sails.io.js library.
we would need to use Model.watch(req) in order to subscribe to Model class. Then we will receive publishCreate() broadcasts.
http://sailsjs.org/documentation/reference/web-sockets/resourceful-pub-sub/watch

How to integrate CKFinder with CKEditor?

How do you integrate CKFinder with the new CKEditor.
It is very underdocumented on the website, and i am literally getting nowhere.
A step by step guide would be greatly appreciate as, as far as i am aware.. this is the only free/good image upload solution for a wysiwyg editor that is any good. Can someone confirm?
Thanks
You can find a tutorial on integrating CKFinder with CKEditor here:
http://www.webshaolin.com/index.php?page=article&articleid=40
Try doing following steps.
1. Download CKEditor and CKFinder. Integrated code may be available on http://dwij.co.in/ckeditor-ckfinder-integration-using-php/
2. Put extracted code of both in one folder inside xampp as below.
3. Create index file (index.html) which will be containing the editor as below code.
<html>
<head>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckfinder/ckfinder.js"></script>
</head>
<body>
<h1>CKEditor CKFinder Integration using PHP</h1>
<textarea id="editor1" name="editor1" rows="10" cols="80"></textarea>
<script type="text/javascript">
var editor = CKEDITOR.replace( 'editor1', {
filebrowserBrowseUrl : 'ckfinder/ckfinder.html',
filebrowserImageBrowseUrl : 'ckfinder/ckfinder.html?type=Images',
filebrowserFlashBrowseUrl : 'ckfinder/ckfinder.html?type=Flash',
filebrowserUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
filebrowserImageUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
filebrowserFlashUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash'
});
CKFinder.setupCKEditor( editor, '../' );
</script>
</body>
</html>
so your folder structure will be something like this:
htdocs
|_integrated
|_ckeditor
| |_config.js
| |_...
|_ckfinder
| |_config.php
| |_...
|_uploads
|_index.html
Now open file config.php inside ckfinder & make following changes:
function CheckAuthentication() {
// WARNING : DO NOT simply return "true". By doing so, you are allowing
// "anyone" to upload and list the files in your server. You must implement
// some kind of session validation here. Even something very simple as...
// return isset($_SESSION['IsAuthorized']) && $_SESSION['IsAuthorized'];
return true; // not good option though; go for sessions
}
$baseUrl = 'http://localhost/integrated/uploads/';
$enabled = true;
$config['SecureImageUploads'] = false;
$config['ChmodFolders'] = 0777 ;
Now open url http://localhost/integrated/ and try uploading image.
Check the documentation site for your server language: http://docs.cksource.com/CKFinder_2.x
For example this part of the PHP docs: http://docs.cksource.com/CKFinder_2.x/Developers_Guide/PHP/CKEditor_Integration
And btw, CKFinder is not free, you must get a license in order to use it.
First you must have a textbox to convert to CKEditor:
<textarea id="newTextArea">Some text</textarea>
Then all you need is some javascript code for the conversion of this texteditor to a CKEditor instance and the integration of this editor with CKFinder.
<script type="text/javascript">
var newCKEdit = CKEDITOR.replace('newTextArea');
CKFinder.setupCKEditor(newCKEdit, '/ckfinder/');
</script>
The second parameter of the setupCKEditor function must be the folder in your website where you uploaded ckfinder.
http://docs.cksource.com/CKFinder_2.x/Developers_Guide/PHP/CKEditor_Integration

Trouble with < in Asp.Net

Ok so I have this string thats going to be an attribute of script tag:
path = "<%= this.ResolveUrl('~/" + path + "') %>";
only problem is when I dynamically generate the tag it turns into:
<script src="<%= this.ResolveUrl('~/Scripts/jquery.js') %>" type="text/javascript"></script>
I don't want the < to be there I want an < to be there...
How can I fix this to generate the < instead of <
I have already tried escaping it by using #"<" and that doesn't work.
Any suggestions?
Use the following line:
path = this.ResolveUrl("~/Scripts/jquery.js");
Tip: Since you are using jQuery you should have a look at the Google AJAX Libraries API. Its basically jQuery and a lot of other AJAX APIs hosted on Google's CDN (so you don't have to). Include it on your page by doing something like:
ScriptManager.RegisterClientScriptInclude(
this,
typeof(Page),
"jQuery",
"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js");
or simply
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>