Polling with angularJs - php

I just want to have polling connection for an current update of my client.
I can't make it work :
var app = angular.module('url', []);
app.factory('Poller', function($http,$q){
return {
poll : function(api){
var deferred = $q.defer();
$http.get(api).then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
}
}
});
app.directive('ngBlur', function(){
return function(scope, elem, attrs){
elem.bind('blur', function(){
scope.$apply(attrs.ngBlur);
})
}
});
app.controller('UrlCtrl', function($scope, $filter, $http, $location, Poller){
$scope.myts = Poller.poll('localhost:8888/mytest.php');
$scope.mydate = $scope.myts.then(function(data){
return $filter('date')(data,'yyyy-MM-dd HH:mm:ss Z');
});
var Repeater = function () {
$scope.$apply(function () {
$scope.myts = Poller.poll('localhost:8888/mytest.php');
$scope.mydate = $scope.myts.then(function(data){
return $filter('date')(data,'yyyy-MM-dd HH:mm:ss Z');
});
});
};
var timer = setInterval(Repeater, 1000);
$scope.urls = [];
$http.get("http://localhost:8888/web-service.php")
.success(function(data) {
data.URLs.forEach(function(url){
$scope.urls.push({
name : url.name,
preferred : false
});
})
})
$scope.$watch('urls', function(){
$scope.chosenURL = $filter('filter')($scope.urls, {preferred:true}).length;
$scope.allchecked = !$filter('filter')($scope.urls, {preferred:false}).length;
}, true)
if($location.path() == ''){ $location.path('/')}
$scope.location = $location;
$scope.$watch('location.path()', function(path){
$scope.statusFilter =
(path == '/active') ? {preferred : true} :
null;
});
$scope.removeUrl = function(index){
$scope.urls.splice(index,1);
}
$scope.addUrl = function(){
$scope.urls.push({
name : $scope.newurl,
preferred : false
});
$scope.newurl = '';
}
$scope.editUrl = function(url){
url.editing = false;
}
$scope.checkAllUrl = function(allchecked){
$scope.urls.forEach(function(url){
url.preferred = allchecked;
})
};
});
mytest.php
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
echo time()*1000;
?>
Here the error I got :
Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME localhost:8888/mytest.php Failed to load resource: the server
responded with a status of 404 (Not Found)
http://localhost:63342/DeliciousJS/js/app.js.map Failed to load
resource: the server responded with a status of 404 (Not Found)
http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js.map
8Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME
localhost:8888/mytest.php OPTIONS localhost:8888/mytest.php
net::ERR_UNKNOWN_URL_SCHEME angular.min.js:97(anonymous function)
angular.min.js:97o angular.min.js:93l angular.min.js:92l.(anonymous
function) angular.min.js:94poll app.js:7(anonymous function)
app.js:32e.$eval angular.min.js:86e.$apply angular.min.js:86Repeater
app.js:31 OPTIONS localhost:8888/mytest.php
net::ERR_UNKNOWN_URL_SCHEME
Why it can't find the url that is working when I try directly on chrome?
Thx for your help

Related

Attempting to delete contact with Axios inside of Vuejs

I am developing an app to store contact information and utilizing Vuejs and Laravel to do it. I am also using the axios library for CRUD functionality.
I have this error on axios.delete() I cannot figure out. This is my Contacts.Vue file:
<script>
export default {
data: function(){
return {
edit:false,
list:[],
contact:{
id:'',
name:'',
email:'',
phone:''
}
}
},
mounted: function(){
console.log('Contacts Component Loaded...');
this.fetchContactList();
},
methods: {
fetchContactList: function(){
console.log('Fetching contacts...');
axios.get('api/contacts').then((response) => {
console.log(response.data);
this.list = response.data;
}).catch((error) => {
console.log(error);
});
},
createContact: function(){
console.log('Creating contact...');
let self = this;
// merging params to the current object
let params = Object.assign({}, self.contact);
// pass above to axios request
axios.post('api/contact/store', params)
.then(function(){
self.contact.name = '';
self.contact.email = '';
self.contact.phone = '';
self.edit = false;
self.fetchContactList();
})
.catch(function(error){
console.log(error);
});
},
showContact: function(id){
let self = this;
axios.get('api/contact/' + id)
.then(function(response){
self.contact.id = response.data.id;
self.contact.name = response.data.name;
self.contact.email = response.data.email;
self.contact.phone = response.data.phone;
})
self.edit = true;
},
updateContact: function(id){
console.log('Updating contact '+id+'...');
let self = this;
// merging params to the current object
let params = Object.assign({}, self.contact);
// pass above to axios request
axios.patch('api/contact/'+id, params)
.then(function(){
self.contact.name = '';
self.contact.email = '';
self.contact.phone = '';
self.edit = false;
self.fetchContactList();
})
.catch(function(error){
console.log(error);
});
},
deleteContact: function(id){
axios.delete('api/contact/'+id)
.then(function(response){
self.fetchContactList();
})
.catch(function(error){
console.log(error);
});
}
}
}
</script>
I am getting a TypeError message saying that self.fetchContactList is not a function.
I know that its saying that the value is not actually a function. There is no typo in the function name. Did I call the function on the wrong object? Should I be using a different property name?
I used self.fetchContactList(); on adding and updating contacts, why will it not work with deleting the contact?
Do I need to add request headers? I didn't have to for the other requests.
If I simply remove self.fetchContactList() it will not function at all.
Despite the error, when I refresh the page, it deletes the contact, but I want the contact deleted upon clicking the delete button.
You don't have let self = this; line in deleteContact function, obviously you would get an error.
alternatively, you can use ES6 arrow functions to avoid assigning this to separate variable like this:
deleteContact: function(id) {
axios.delete('api/contact/'+id)
.then((response) => {
this.fetchContactList();
})
.catch((error) => {
console.log(error);
});
}

AngularJS: Uploading file via angular JS

My current scenario is: I've doing nesting repetition like follow:
$scope.uploadPic = function(file)
{
alert($scope.taskdetails.id); //task_id e.g 21
alert($rootScope.job_id); //job_id e.g 12
file.upload = Upload.upload(
{
url: 'http://localhost/mobile-data/upload_file.php',
data: {
file: file,
task_id: $scope.taskdetails.id,
job_id: $rootScope.job_id
},
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
but on my upload_file.php i can't receive the values for:
task_id: $scope.taskdetails.id,
job_id: $rootScope.job_id
in console.log they are working fine. but on server side it is not receiving. here is code of my upload_file.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('content-type: application/json; charset=utf-8');
$_POST = json_decode(file_get_contents('php://input'), true);
$task_id = $_POST["task_id"];
$file = $_FILES["file"];
$job_id = $_POST["job_id"];
var_dump($task_id);
var_dump($job_id);
but on var_dump it only print null. Help me to receive the values correctly..
In your php file remove the decode line that is:
$_POST = json_decode(file_get_contents('php://input'), true);
You dont need to decode because you are not receiving data into JSON encoded array...

Angular ui-router resolve, http success, stateParams

My goal to achieve is:
first to insert new database record with http post, resolve with stateProvider and grab the new id and change view and stateParams.
i have this code for my http post service
myApp.service('postService', ['$http', function($http) {
this.insertNew = function() {
$http.post('create_new.php')
.success(function(data) {
return data;
});
};
create_new.php returns the ID like this (it works, proved with console)
return json_encode($data);
and the stateProvider looks like this (section)
$stateProvider
.state('newRecord', {
resolve: {
newArtID: ['postService',
function(postService) {
return postService.insertNew();
}]
},
params: {
artID: <-- new ID from DB
},
i did tests with stateParams in serval variations (in resolve and by params). how can i bring the new ID to stateParams, so i can access from the views?
Thanks for any help!
I'm not so sure your oder of operations is correct. params is for when you already have that data. You should return the data from your resolve, then you can access it in your scope, for ex:
Service:
.service('postService', function ($http) {
this.insertNew = function () {
return $http.post('create_new.php').then(function (data) {
return data;
});
}
})
Route:
$stateProvider
.state('newRecord', {
views: {
"main": {
controller: 'SomeCtrl',
templateUrl: '...'
}
},
resolvedId: {
newArtID: function (postService) {
return postService.insertNew().then(function (response) {
return response;
});
}
}
})
Controller:
.controller('SomeCtrl', function (resolvedId) {
var newID = resolvedId.id; //depending on what is returned
});

AngularJS service for php files

i am trying to create a service for angular which should get the data from a php that generates a json. Right now my service looks like this
fixEvents.service('contactService', function($http, $q) {
this.getallContact = function() {
var json = $q.defer();
$http.get('models/contact.getall.json')
.success(function(data) {
json.resolve(data);
})
.error(function() {
json.reject();
});
return json.promise;
};
});
and my controller looks like this
fixEvents.controller('contactCtrl', function($scope, contactService) {
$scope.title = "CONTACT";
$scope.jsonContact = contactService.getallContact();
$scope.showMessage = function() {
alert($scope.jsonContact.length);
}
});
the problem is my jsonContact does not get any result. It seems to be undefined. Is there something i did wrong? And by the way is there a better way to do this ? Thank you, Daniel!
You have to use .then back in the controller to work with the data:
var jsonContactPromise = contactService.getallContact();
jsonContactPromise.then(function(data) {
$scope.jsonContact = data
}, function(error) {
console.log("ERROR: " + error);
});

weird node.js and redis behaviour

I've got a problem that defies explanation. Here's what i want:
Client connects to node server through socket.io, sends his SID
Redis verifies if said SID is in its store, if not, don't emit 'authenticated', if the sid is in the store, then emit 'authenticated'
Upon receiving the authentication, the extra options are given
Sounds pretty straightforward, and it should be. However this happens:
Client connects with a SID thats in the redis store
Node.js server verifies that the SID is in the store but fails to emit said 'authenticated'
However, when i restart the node server, everything seems to work just fine :S. But when i proceed to remove the key from the store, and add it again (by ?auth and ?logout) the 'authenticated' is again not emitted.
Client code:
<?php
session_start();
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
require "./libraries/Predis.php";
if(isset($_GET['logout'])) {
session_regenerate_id();
}
$sid = sha1(session_id());
$redis = new Predis\Client();
echo "<h1>SID: " . $sid . "</h1>";
if(isset($_GET['auth'])) {
$redis->set($sid, mt_rand(1,20000));
$redis->expire($sid, 1800);
echo "auth set<br />";
}
if ($redis->get($sid)) {
// he is authenticad, show something else
echo "auth found<br />";
}
?>
<html>
<head>
<title>Node Test VTclient</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://the_server.dev:11337/socket.io/socket.io.js"></script>
</head>
<body>
<p id="text">access denied</p>
<script type="text/javascript">
var connected = false;
var authenticated = false;
if(typeof io == 'undefined') {
trigger_error();
} else {
var socket = io.connect('http://vtvserver.dev:11337/', {
'reconnection delay' : 1,
'max reconnection attempts' : 1
});
socket.on('connect', function (data) {
connected = true;
socket.emit('success_connect',{sid: '<?php echo $sid; ?>'});
$('#text').html('connected');
socket.on('get_bids', function (data) {
$('#bids').html('');
if(typeof data === 'object') {
$.each(data.rows, function(key, value) {
add_bid(value.bid_id, value.bid_amount);
});
}
}).on('reconnecting', function (reason) {
trigger_error(reason);
$('#text').html('disconnected');
socket.disconnect();
}).on('authenticated', function(data) {
$('#text').html('authorised!');
// successful auth
$('#bidding').show();
}).on('disconnect', function (data) {
connected = false;
}).on('bid_placed', function (data) {
add_bid(data.id, data.amount);
}).on('own_bid_placed', function(data){
if(!data.error) {
alert('bieding geplaatst!');
} else {
alert('Uw bieding is ongeldig.');
}
});
});
}
function trigger_error(reason) {
$('#text').html('Server is down...');
}
function add_bid(id, amount) {
$('#bids').append($('<option>', { value : id }).text(amount));
}
$(function() {
$('#disconnect').click(function() {
if(connected === true) {
socket.disconnect();
$('#text').html('Disconnected from server.');
}
});
$('#bid').click(function() {
var amount = $('#amount').val();
// commit the bid to the server
socket.emit('add_bid', {amount: amount});
});
})
</script>
<label for="bids">Biedingen:</label>
<select name="bids" id="bids" multiple='multiple' style='width:100px; height:150px'></select>
<fieldset style="display:none" id="bidding">
<legend>Plaats bieding</legend>
<label for="amount"><Bedrag: </label><input type="text" id="amount" name="amount" value='0' />
<button id="bid">Bied</button>
</fieldset>
<button id="disconnect">Disconnect</button>
</body>
Server code:
var
cfg = require("./config").cfg(),
sys = require("sys"),
url = require("url"),
http = require("http"),
qs = require("querystring"),
redis = require("redis"),
redis_client = redis.createClient(cfg.redis.port, cfg.redis.host),
express = require("express"),
mysql = require("./node_modules/mysql"),
//ch = require("./node_modules/channel").channel(cfg.msg_backlog, cfg.msg_truncate),
sio = require('./node_modules/socket.io');
//require ('./node_modules/sherpa');
//require ('./node_modules/log');
require ('./node_modules/simplejsonp');
redis_client.on("error", function (err) {
console.log("REDIS error: " + err);
});
var app = express();
app.configure(function(){
});
app.get('/',
function (req,res) {
if (req.headers['referer']) {
log(req.connection.remoteAddress + " / " + req.headers['referer']);
}
else {
log(req.connection.remoteAddress + " /");
}
res.writeHead(307, {'Location':'http://' + cfg.domain});
res.end();
});
app.listen(cfg.server_port, cfg.server_public_ip);
/* Create the IO server */
var server = http.createServer(app);
var io = sio.listen(server);
// minify the browser socket io client
io.enable('browser client minification');
server.listen(11337);
io.set('log level', 2);
io.sockets.on('disconnect', function(data) {
console.log('client disconnected');
});
/**
* Enable authentication
* #param {[type]} handshakeData [description]
* #param {Function} callback [description]
* #return {[type]} [description]
*/
// Anonymous or authenticaed user?
io.on('connection', function (socket) {
var sql_client = mysql.createClient({
host : cfg.database.server,
user : cfg.database.user,
password : cfg.database.pass,
database : cfg.database.primary
});
console.log('incoming connection');
socket.emit('access', 'granted');
socket.on('success_connect', function(data) {
console.log('Client connected: ' + data.sid);
sql_client.query('SELECT * FROM `bids`',function(error, results) {
if(error) {
console.log('Error: ' + error);
return false;
}
console.log('emitting get_bids...');
socket.emit('get_bids', {rows: results});
});
// if the user is authenticated, flag it as such
redis_client.get(data.sid, function(err, reply) {
var authenticated = false;
if(err) {
console.log("Fatal error: " + err);
}
console.log('Got response from redis...');
if(reply !== null) {
console.log('auth succesful for '+data.sid);
socket.emit('authenticated', { sid : data.sid});
authenticated = true;
}
// LEFT JOIN user_bids ON user_bids_bid_id = bid_id
if(authenticated === true) {
// safest way: only listen for certain commands when the user is autenticated
socket.on('add_bid', function(data) {
var amount = data.amount;
var values = [amount];
var error = false;
// validate the amount
var regexp = new RegExp(/^\d{1,5}(\.\d{1,2})?$/);
if(typeof amount === 'undefined' || amount < 1.00 || !amount.match(regexp)) {
error = 'invalid_bid';
}
socket.emit('own_bid_placed', {amount: amount, error : error});
if(!error) {
sql_client.query('INSERT INTO `bids` SET bid_amount = ?',values,function(error, results) {
if(error) {
console.log('Error: ' + error);
}
console.log('Inserted: ' + results.affectedRows + ' row.');
console.log('Id inserted: ' + results.insertId);
io.sockets.emit('bid_placed', {id: results.insertId, amount: amount});
});
}
});
}
});
});
sql_client.end();
socket.on('disconnect', function(data) {
console.log('Client disconnected');
});
});
console.log('Server running at http://'+cfg.server_public_ip+':'+cfg.server_port+'/');
I fixed it by creating the redis client when a client connects:
io.on('connection', function (socket) {
var redis_client = redis.createClient(cfg.redis.port, cfg.redis.host);
});

Categories