i am trying use the Pusher but have a trouble.
i am doing so:
into PHP so:
$pusher = new Pusher(env("PUSHER_APP_KEY"), env("PUSHER_SECRET"), env("PUSHER_APP_ID"), array('cluster' => env("PUSHER_CLUSTER")));
$pusher->trigger('buy', 'compra-paga', [
"id"=>$external_reference,
"status"=>$status
]
);
it gear the follow out (example):
Pusher : : [
"Event recd",
{
"event":"compra-paga",
"channel":"buy",
"data": {
"id":18,
"status":"approved"
}
}
]
In the front end (JS) i have the follow:
var key = "my_key";
var id_buy = localStorage.getItem("id_buy");
console.log(id_buy);
var pusher = new Pusher(key, {
cluster: 'us2'
});
var channel = pusher.subscribe('buy');
channel.bind("compra-paga", function(data) {
console.log(
id_buy,
jQuery.parseJSON(data),
data,
data.id
);
var id = localStorage.getItem("id_buy")
if (id === data.id)
$("#pgto").html('<h1 class="midiArea">Recebemos seu pagamento!</h1>');
});
the problem:
no one console.log works.
it appears that nothing out int screem.
Related
I have the following cloud code on parse to update a user image but I can't seem to get it saving. help!
in php
ParseCloud::run("updateUserImage", array("file" => $_FILES['image'], "objectId" => $objectId, "name" => $_FILES['image']['name'], "type"=> $_FILES['image']['type'] ));
in cloud code
Parse.Cloud.define("updateUserImage", async (request) => {
const { file, objectId, name, type} = request.params;
var fileData = request.params.file;
var fileSave = new Parse.File(name, fileData);
fileSave.save();
var User = Parse.Object.extend(Parse.User);
var query = new Parse.Query(User);
let result = await query.get(objectId, { useMasterKey: true });
if (!result) new Error("No user found!");
result.set("profilePicture", fileSave);
try {
result.save(null, { useMasterKey: true });
return "User updated successfully!";
} catch (e) {
return e.message;
}
});
How can i get phonegap-plugin-push senderID
i tried looking on internet but none of them seems to be working , may be google has updated something .
https://console.developers.google.com
have created a new project here .
after i went inside dashboard .
I see the message No APIs or services are enabled .
can anyone please guide .
this is my code where i'm trying to replace my sender id
console.log('calling push init');
var push = PushNotification.init({
"android": {
"senderID": "XXXXXXXX"
},
"browser": {},
"ios": {
"sound": true,
"vibration": true,
"badge": true
},
"windows": {}
});
console.log('after init');
push.on('registration', function(data) {
console.log('registration event: ' + data.registrationId);
var oldRegId = localStorage.getItem('registrationId');
if (oldRegId !== data.registrationId) {
// Save new registration ID
localStorage.setItem('registrationId', data.registrationId);
// Post registrationId to your app server as the value has changed
}
var parentElement = document.getElementById('registration');
var listeningElement = parentElement.querySelector('.waiting');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
});
push.on('error', function(e) {
console.log("push error = " + e.message);
});
push.on('notification', function(data) {
console.log('notification event');
navigator.notification.alert(
data.message, // message
null, // callback
data.title, // title
'Ok' // buttonName
);
});
Thanks in advance .
UPDATED.
I'm using codeigniter and i want to fetch data from node js api but i need to be able to get it by codeigniter's models, i also need to be able to pass parameters to node js.
Here is what i've done so far - it's working fine - but i can't figure how to pass parameter to the SQL query - from the model to node js.
If it's not clear up to now - please review the code - i added some explanations there also.
And here is the model (users_model.php)
public function node_get($id)
{
$foo = file_get_contents('http://localhost:3000/'.$id);
return $foo ;
}
Here the node.js app (app.js)
var mysql = require('mysql');
var con = mysql.createConnection({
host: "something",
user: "something",
password: "something",
database: "something"
});
var user_id; <---------------------------How can i pass this in the model?
var user_data;
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM users_data WHERE user_id ="+user_id, function
(err,
result, fields) {
if (err) throw err;
user_data = result;
// console.log(user_data);
});
});
app.get('/', function(req, res){
res.send(JSON.stringify(user_data, null, 3));
});
app.listen(3000);
Got it....
var express = require('express');
var app = express();
var helmet = require('helmet');
var port = process.env.PORT || 3000;
var mysql = require('mysql');
app.use(helmet.hidePoweredBy());
app.use(helmet.xssFilter());
app.use(helmet.frameguard);
app.get('/:user_id', function(req, res){
var user_id = req.params.user_id;
if(user_id == null){
user_id =1;
}
var con = mysql.createConnection({
host: "something",
user: "something",
password: "something",
database: "something"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM users_data WHERE user_id ="+user_id, function (err, result, fields) {
if (err) throw err;
res.send( JSON.stringify(result));
});
});
});
app.listen(port);
I am using this code to save user gallery images on my website.First when user logged in then all gallery images loads and when user will select any image then i need to save that image in a directory. This is my code. Image is saveing with the name but image size is zero.
$file = file_get_contents('https://graph.facebook.com/[Fb-Photo-ID]/picture?width=378&height=378&access_token=[Access-Token]');
$img = file_put_contents($target_dir['path'].'/'."facebook3.jpg",$file);
This is code of image gallery.
<script>
/**
* This is the getPhoto library
*/
function makeFacebookPhotoURL( id, accessToken ) {
//alert(id);
return 'https://graph.facebook.com/v2.6/' + id + '/picture?access_token=' + accessToken;
}
function login( callback ) {
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
if (callback) {
callback(response);
}
} else {
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'publish_actions,user_location,user_photos,email'} );
}
function getAlbums( callback ) {
FB.api(
'/me/albums',
{fields: 'id,cover_photo'},
function(albumResponse) {
console.log( ' got albums ' );
if (callback) {
callback(albumResponse);
console.log(albumResponse);
}
}
);
}
function getPhotosForAlbumId( albumId, callback ) {
//alert(albumId);
console.log(albumId);
FB.api(
'/'+albumId+'/photos',
{fields: 'id'},
function(albumPhotosResponse) {
console.log( ' got photos for album ' + albumId );
if (callback) {
callback( albumId, albumPhotosResponse );
}
}
);
}
function getLikesForPhotoId( photoId, callback ) {
FB.api(
'/'+albumId+'/photos/'+photoId+'/likes',
{},
function(photoLikesResponse) {
console.log(photoLikesResponse);
if (callback) {
callback( photoId, photoLikesResponse );
}
}
);
}
function getPhotos(callback) {
var allPhotos = [];
var accessToken = '';
login(function(loginResponse) {
accessToken = loginResponse.authResponse.accessToken || '';
//console.log(accessToken);
getAlbums(function(albumResponse) {
var i, album, deferreds = {}, listOfDeferreds = [];
for (i = 0; i < albumResponse.data.length; i++) {
album = albumResponse.data[i];
deferreds[album.id] = $.Deferred();
listOfDeferreds.push( deferreds[album.id] );
getPhotosForAlbumId( album.id, function( albumId, albumPhotosResponse ) {
var i, facebookPhoto;
for (i = 0; i < albumPhotosResponse.data.length; i++) {
facebookPhoto = albumPhotosResponse.data[i];
allPhotos.push({
/* 'id' : facebookPhoto.id,
'added' : facebookPhoto.created_time, */
'url' : makeFacebookPhotoURL( facebookPhoto.id, accessToken )
});
}
deferreds[albumId].resolve();
});
}
$.when.apply($, listOfDeferreds ).then( function() {
if (callback) {
callback( allPhotos );
}
}, function( error ) {
if (callback) {
callback( allPhotos, error );
}
});
});
});
}
</script>
<script>
/**
* This is the bootstrap / app script
*/
// wait for DOM and facebook auth
var docReady = $.Deferred();
var facebookReady = $.Deferred();
$(document).ready(docReady.resolve);
window.fbAsyncInit = function() {
FB.init({
appId : '00000000000',
channelUrl : '//conor.lavos.local/channel.html',
status : true,
cookie : true,
xfbml : true
});
facebookReady.resolve();
};
$.when(docReady, facebookReady).then(function() {
if (typeof getPhotos !== 'undefined') {
getPhotos( function( photos ) {
//console.log(photos);
var str= JSON.stringify(photos);
var contact=jQuery.parseJSON(str);
$.each( photos, function( index, value ){
$.each( value, function( index1, value1 ){
console.log(value);
//console.log( index1+value1);
//console.log( index1+value1);
//console.log( index1+value1);
$("#images").append('<img height="100" width="150" src='+value1+' />');
$("a.myimg img").click(function()
{
var imgSrc = $(this).attr('src');
$("#fbimg").val(imgSrc);
});
});
});
});
}
});
</script>
The problem is that you are using FB API in incorrect way.
You should have version of your API request
check access_token -> whether it has correct wright ( user_photos )
in such way of request you won't receive image content. You can receive only link on static image.
So only after receiving of image - you can save it
Your link should be like :
https://graph.facebook.com/v2.6/[photo_Id]/picture?access_token=[access_token_with_wrights]
this will return JSON data kind of :
{
"data": {
"is_silhouette": false,
"url": "https://scontent.xx.fbcdn.net/[image_url]"
}
}
read more here and you can add additional params for thumbs ( aka "images" )
UPDATE
so in your way it would be like :
$jsonstring = json_decode(file_get_contents("https://graph.facebook.com/v2.6/[photo_Id]?fields=picture,images&access_token=[access_token_with_wrights]
"));
$file = file_get_contents($jsonstring['images'][0]['source']) /* chose your size */
$img = file_put_contents($target_dir['path'].'/'."facebook3.jpg",$file);
OR use FB PHP SDK
UPDATE #2
If you received static link to image from JS => just use it, not the graphApi request. It means that you can SEND ALREADY RECEIVED LINKS to server side. And they should be like https://scontent.xx.fbcdn.net/XXXXXX and after receiving them on server side you can just use them. and make
$file = file_get_contents("https://scontent.xx.fbcdn.net/");
But link should not be on http://graph.facebook.com!
UPDATE 3
Yes, it's correct request ( from question ).
JS code for images with static path:
FB.api(
'/' + albumId + '/photos',
{ fields: 'id,images' }, /* main is images array in response */
function ( albumPhotosResponse ) {
console.log( ' got photos for album ' + albumId );
if ( callback ) {
callback( albumId, albumPhotosResponse );
}
} );
parse the path for image from there.
I've been trying for days to get this working and I just cannot figure out why when I have my view to destroy a model which belongs to a collection (which properly has a url attribute for the beginning fetch of models' data), only fires the destroy 'event' which is bubbled up to the collection for easy binding by my list view. But it does not ever send an actual DELETE request or any request to the server at all. Everywhere I look, I see everyone using either the collection's url attr, or urlRoot if the model is not connected to a collection. I've even tested before the actual this.model.destroy() to check the model < console.log(this.model.url());
I have not overwritten the destroy nor sync methods for backbone. Also each model does have an id attribute which is populated via the collection's fetch (from database records).
The destroy takes place in the list item view, and the collection's "destroy" event is bound in the list view. All that works well (the event handling), but the problem, again, is there's no request to the server.
I was hoping that backbone.js would do it automatically. That was what the documentation implies, as well as the numerous examples everywhere.
Much thanks to anyone who can give some useful input.
FYI: I'm developing on wampserver PHP 5.3.4.
ListItemView = BaseView.extend({
tagName: "li",
className: "shipment",
initialize: function (options) {
_.bindAll(this);
this.template = listItemTemplate;
this.templateEmpty = listItemTemplateEmpty;
},
events: {
'click .itemTag' : 'toggleData',
'click select option' : 'chkShipper',
'click .update' : 'update',
'click button.delete' : 'removeItem'
},
// ....
removeItem: function() {
debug.log('remove model');
var id = this.model.id;
debug.log(this.model.url());
var options = {
success: function(model, response) {
debug.log('remove success');
//debug.log(model);
debug.log(response);
// this.unbind();
// this.remove();
},
error: function(model, response) {
debug.log('remove error');
debug.log(response);
}
};
this.model.destroy(options);
//model.trigger('destroy', this.model, this.model.collection, options);
}
});
Collection = Backbone.Collection.extend({
model: Model,
url: '?dispatch=get&src=shipments',
url_put : '?dispatch=set&src=shipments',
name: 'Shipments',
initialize: function () {
_.bindAll(this);
this.deferred = new $.Deferred();
/*
this.fetch({
success: this.fetchSuccess,
error: this.fetchError
});
*/
},
fetchSuccess: function (collection, response) {
collection.deferred.resolve();
debug.log(response);
},
fetchError: function (collection, response) {
collection.deferred.reject();
debug.log(response);
throw new Error(this.name + " fetch failed");
},
save: function() {
var that = this;
var proxy = _.extend( new Backbone.Model(),
{
url: this.url_put,
toJSON: function() {
return that.toJSON();
}
});
var newJSON = proxy.toJSON()
proxy.save(
newJSON,
{
success: that.saveSuccess,
error: that.saveError
}
);
},
saveSuccess: function(model, response) {
debug.log('Save successful');
},
saveError: function(model, response) {
var responseText = response.responseText;
throw new Error(this.name + " save failed");
},
updateModels: function(newData) {
//this.reset(newData);
}
});
ListView = BaseView.extend({
tagName: "ul",
className: "shipments adminList",
_viewPointers: {},
initialize: function() {
_.bindAll(this);
var that = this;
this.collection;
this.collection = new collections.ShipmentModel();
this.collection.bind("add", this.addOne);
this.collection.fetch({
success: this.collection.fetchSuccess,
error: this.collection.fetchError
});
this.collection.bind("change", this.save);
this.collection.bind("add", this.addOne);
//this.collection.bind("remove", this.removeModel);
this.collection.bind("destroy", this.removeModel);
this.collection.bind("reset", this.render);
this.collection.deferred.done(function() {
//that.render();
that.options.container.removeClass('hide');
});
debug.log('view pointers');
// debug.log(this._viewPointers['c31']);
// debug.log(this._viewPointers[0]);
},
events: {
},
save: function() {
debug.log('shipments changed');
//this.collection.save();
var that = this;
var proxy = _.extend( new Backbone.Model(),
{
url: that.collection.url_put,
toJSON: function() {
return that.collection.toJSON();
}
});
var newJSON = proxy.toJSON()
proxy.save(
newJSON,
{
success: that.saveSuccess,
error: that.saveError
}
);
},
saveSuccess: function(model, response) {
debug.log('Save successful');
},
saveError: function(model, response) {
var responseText = response.responseText;
throw new Error(this.name + " save failed");
},
addOne: function(model) {
debug.log('added one');
this.renderItem(model);
/*
var view = new SB.Views.TicketSummary({
model: model
});
this._viewPointers[model.cid] = view;
*/
},
removeModel: function(model, response) {
// debug.log(model);
// debug.log('shipment removed from collection');
// remove from server
debug.info('Removing view for ' + model.cid);
debug.info(this._viewPointers[model.cid]);
// this._viewPointers[model.cid].unbind();
// this._viewPointers[model.cid].remove();
debug.info('item removed');
//this.render();
},
add: function() {
var nullModel = new this.collection.model({
"poNum" : null,
"shipper" : null,
"proNum" : null,
"link" : null
});
// var tmpl = emptyItemTmpl;
// debug.log(tmpl);
// this.$el.prepend(tmpl);
this.collection.unshift(nullModel);
this.renderInputItem(nullModel);
},
render: function () {
this.$el.html('');
debug.log('list view render');
var i, len = this.collection.length;
for (i=0; i < len; i++) {
this.renderItem(this.collection.models[i]);
};
$(this.container).find(this.className).remove();
this.$el.prependTo(this.options.container);
return this;
},
renderItem: function (model) {
var item = new listItemView({
"model": model
});
// item.bind('removeItem', this.removeModel);
// this._viewPointers[model.cid] = item;
this._viewPointers[model.cid] = item;
debug.log(this._viewPointers[model.cid]);
item.render().$el.appendTo(this.$el);
},
renderInputItem: function(model) {
var item = new listItemView({
"model": model
});
item.renderEmpty().$el.prependTo(this.$el);
}
});
P.S... Again, there is code that is referenced from elsewhere. But please note: the collection does have a url attribute set. And it does work for the initial fetch as well as when there's a change event fired for saving changes made to the models. But the destroy event in the list-item view, while it does trigger the "destroy" event successfully, it doesn't send the 'DELETE' HTTP request.
Do your models have an ID? If not, the HTTP request won't be sent. –
nikoshr May 14 at 18:03
Thanks so much! Nikoshr's little comment was exactly what I needed. I spent the last 5 hours messing with this. I just had to add an id to the defaults in my model.