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.
Related
Okay so I have an uploader script that I customized and it works great. I have 2 more steps that I need to do for it to be complete and it is beyond my scope and I have read and tried numerous things and still am not getting the results that I want.
Again only code that is releative to my issue will be posted as the code works perfect and does not need any changing with the exception of trying to get a value from AJAX to PHP.
FULL JS FILE BELOW:
jQuery(document).ready(function () {
var img_zone = document.getElementById('img-zone'),
collect = {
filereader: typeof FileReader != 'undefined',
zone: 'draggable' in document.createElement('span'),
formdata: !!window.FormData
},
acceptedTypes = {
'image/png': true,
'image/jpeg': true,
'image/jpg': true,
'image/gif': true
};
// Function to show messages
function ajax_msg(status, msg) {
var the_msg = '<div class="alert alert-'+ (status ? 'success' : 'danger') +'">';
the_msg += '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>';
the_msg += msg;
the_msg += '</div>';
$(the_msg).insertBefore(img_zone);
}
// Function to upload image through AJAX
function ajax_upload(files) {
$('.progress').removeClass('hidden');
$('.progress-bar').css({ "width": "0%" });
$('.progress-bar span').html('0% complete');
var productTestID = "333746240";
var formData = new FormData(this);
formData.append('productTestID',productTestID);
//formData.append('any_var', 'any value');
for (var i = 0; i < files.length; i++) {
//formData.append('img_file_' + i, files[i]);
formData.append('img_file[]', files[i]);
}
$.ajax({
url : "upload.php", // Change name according to your php script to handle uploading on server
type : 'post',
data : formData,
dataType : 'json',
processData: false,
contentType: false,
error : function(request){
ajax_msg(false, 'An error has occured while uploading photo.');
},
success : function(json){
var img_preview = $('#img-preview');
var col = '.col-sm-2';
$('.progress').addClass('hidden');
var photos = $('<div class="photos"></div>');
$(photos).html(json.img);
var lt = $(col, photos).length;
$('col', photos).hide();
$(img_preview).prepend(photos.html());
$(col + ':lt('+lt+')', img_preview).fadeIn(2000);
if(json.error != '')
ajax_msg(false, json.error);
},
progress: function(e) {
if(e.lengthComputable) {
var pct = (e.loaded / e.total) * 100;
$('.progress-bar').css({ "width": pct + "%" });
$('.progress-bar span').html(pct + '% complete');
}
else {
console.warn('Content Length not reported!');
}
}
});
}
// Call AJAX upload function on drag and drop event
function dragHandle(element) {
element.ondragover = function () { return false; };
element.ondragend = function () { return false; };
element.ondrop = function (e) {
e.preventDefault();
ajax_upload(e.dataTransfer.files);
}
}
if (collect.zone) {
dragHandle(img_zone);
}
else {
alert("Drag & Drop isn't supported, use Open File Browser to upload photos.");
}
// Call AJAX upload function on image selection using file browser button
$(document).on('change', '.btn-file :file', function() {
ajax_upload(this.files);
});
// File upload progress event listener
(function($, window, undefined) {
var hasOnProgress = ("onprogress" in $.ajaxSettings.xhr());
if (!hasOnProgress) {
return;
}
var oldXHR = $.ajaxSettings.xhr;
$.ajaxSettings.xhr = function() {
var xhr = oldXHR();
if(xhr instanceof window.XMLHttpRequest) {
xhr.addEventListener('progress', this.progress, false);
}
if(xhr.upload) {
xhr.upload.addEventListener('progress', this.progress, false);
}
return xhr;
};
})(jQuery, window);
});
So the above code is from the .js file. The script uploads multiple selected files, which works fine. From what I have read, in order to get additional values sent to PHP you have to use the .append(), which is what I have done below. I created the var productTestID and gave it a value and then added it to the formData using the append().
My issue is how do I read it in PHP?
I have tried $_POST[productTestID] and get no results at all. I even tried doing an isset() and it comes back not set.
So what do I need to do in my PHP code to read or extract that value? Below is an excerpt from my upload.php file and like I said the file uploads work and this is how they are being accessed.
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$error = '';
$img = '';
$dir = dirname($_SERVER['SCRIPT_FILENAME'])."/". DIR_WS_IMAGES . "upload/";
$extensions = array("jpeg","jpg","png");
foreach($_FILES['img_file']['tmp_name'] as $key => $tmp_name )
Further down in my upload.php file:
//MOVE TO FINAL LOCATION
$uploaded_file = $dir.$file_name;
if (rename($uploaded_file, $uniqueFileName))
{
$productTestID = $_POST['productTestID'];
}
$img .= '<div class="col-sm-2"><div class="thumbnail">';
$img .= '<img src="'.$dir.$file_name.'" />'.$uploaded_file . '<br>' .$fileName.'<br>'.$uniqueFileName.'<br>This Product Id is:';
$img .= $productTestID;
$img .= '</div></div>';
}
Thank You,
Shawn Mulligan
Good day,
I am trying to create a script that loads my Browser Geolocation and following sends it to a file that saves it.
The problem is. The data does not get send.
And an even bigger problem is that I have tried many things but I am quite clueless.
I added several alerts but the alerts do not show up.
What should the script do?
Run once every five seconds and requesting your GeoLocation.
When you click accept on your phone and accept for all from this source you will have an active GPS alike tracking.
The code :
<script type="text/javascript">
function success(position) {
///SaveActiveGeoLocation();
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(success, error);
}
else{
error('not supported');
}
function SaveGeoLocation(){
var Lat = position.coords.latitude;
var Lon = position.coords.longitude;
var Accuracy = position.coords.accuracy;
///######## SENDING THE INFORMATION BY AJAX
$.ajax({
type : "POST", /// **** SEND TYPE
url : "savegeo.php", /// **** TARGET FILE TO FETCH THE DATA
data : {
'Lat' : Lat,
'Lon' : Lon,
'GeoAccuracy' : Accuracy
},
///######## IN CASE OF SUCCESS
success:function(response){
if( response == "ok" ){
alert('SEND!');
}
else{
alert( "Response = " + response );
}
}
}
);
}
$(document).ready(function() {
$.ajaxSetup({
cache: false
}); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
///alert('HOI!');
SaveGeoLocation();
}, 5000);
// the "10000" here refers to the time to refresh the div. it is in milliseconds.
/// **** DEFAULT LOADING
///SaveGeoLocation();
});
</script>
The file that saves the send POST data :
<?php
include('function.geolocation.class.php');
$geo = new GeoLocation();
$Lat = $_POST['Lat'];
$Lon = $_POST['Lon'];
$GeoAccuracy = $_POST['GeoAccuracy'];
$IP = $geo->GetIP();
$file = 'location.txt';
$address = $geo->getAddress($Lat, $Lon);
$contents = $Lat.'|'.$Lon.'|'.$IP.'|'.$GeoAccuracy.'|'.date('Y-m-d H:i:s').'|'.$address.PHP_EOL;
$handle = fopen($file, 'a');
fwrite($handle, $contents);
fclose($handle);
echo 'ok';
?>
One problem I can see is the variable position does not exists in the context of the SaveGeoLocation method
function success(position) {
//SaveActiveGeoLocation();
window.position = position;
}
function SaveGeoLocation() {
if (!window.position) {
return;
}
//your stuff
}
There is no need to call SaveGeoLocation using interval, you can call SaveGeoLocation from the success callback like
function success(position) {
SaveActiveGeoLocation(position);
}
function SaveGeoLocation(position) {
//your stuff
}
If you want to save the location continuously
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
function saveLocation() {
navigator.geolocation.getCurrentPosition(success, error);
}
function success(position) {
var Lat = position.coords.latitude;
var Lon = position.coords.longitude;
var Accuracy = position.coords.accuracy;
///######## SENDING THE INFORMATION BY AJAX
$.ajax({
type: "POST", /// **** SEND TYPE
url: "savegeo.php", /// **** TARGET FILE TO FETCH THE DATA
data: {
'Lat': Lat,
'Lon': Lon,
'GeoAccuracy': Accuracy
},
///######## IN CASE OF SUCCESS
success: function (response) {}
}).done(function (response) {
if (response == "ok") {
alert('SEND!');
} else {
alert("Response = " + response);
}
}).always(function () {
setTimeout(saveLocation, 5000)
});
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
}
if (navigator.geolocation) {
saveLocation();
} else {
error('not supported');
}
});
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.
In my siteweb I'm implementing authentication with Facebook API.
<fb:login-button onlogin="fbLoginEvent(arguments)">Enter with Facebook</fb:login-button>
My function fbLoginEvent:
function fbLoginEvent( args ) {
//console.log( "fbLogin", args );
//var session = FB.getSession();
var session = FB.getAuthResponse();
if (session) {
fbCheckSession(session, function(data) {
if (data.result) {
fbLoginNow();
} else {
$('#facebook-register').data("overlay").load();
}
});
}
}
And my function for check the session:
var fbLogin = { status: false, uid: 0, access_token: "" };
function fbCheckSession( session, callback ) {
if ( session && $.type(callback) == "function" ) {
ajaxCall( "facebook", "check_session", {uid: session.uid, token: session.access_token}, function(data){
if ( data.result ) {
fbLogin.status = true;
fbLogin.fbuid = session.uid;
fbLogin.uid = data.info.id;
fbLogin.access_token = session.access_token;
callback( { result: true, info: { name: data.info.name, fbLogin: fbLogin } } );
} else {
callback( { result: false } );
}
});
}
}
I made various checks and I have noticed that uid and tokens value are empty.
Any solution?
Thk
You made a mistake by assigning session variable to FB.getAuthResponse function of JS-SDK
Use
var session = FB.getAuthResponse();
Instead of
var session = FB.getAuthResponse
You also using incorrect properties names, authResponse use the same format as FB.getLoginStatus not in format returned by getSession of previous version of JS-SDK.
uid named userID, and access_token is accessToken
I've got a problem which I can't seem to solve.
I'm currently implementing a an AJAX-function similar to the one Twitter uses - that fetch new posts on scrolling.
The jQuery looks something like this:
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height()){
$('div#ajaxloader').show();
$.ajax({
url: "loader.php?lastid=" + $(".container:last").attr("id"),
success: function(html){
if(html){
$("#main").append(html);
$('div#ajaxloader').hide();
}else{
$('div#ajaxloader').html('No more posts to show.');
}
}
});
}
});
Now the problem; if the user scrolls really fast and the database is doing it's work quickly - the jQuery doesn't seem to be able to send the correct id as a query fast enough - which results in double-posts.
Anyone have a good idea on how to prevent this?
Try This:
var runningRequest = 0;
$(window).scroll(function(){
if(runningRequest <1){
if($(window).scrollTop() == $(document).height() - $(window).height()){
runningRequest++;
$('div#ajaxloader').show();
$.ajax({
url: "loader.php?lastid=" + $(".container:last").attr("id"),
success: function(html){
runningRequest--;
if(html){
$("#main").append(html);
$('div#ajaxloader').hide();
}else{
$('div#ajaxloader').html('No more posts to show.');
}
}
error: function(){runningRequest--;}
});
}
}
});
I would set a boolean to true right before making my request, and whenever the request completes I'd set it back to false. Then I'd wrap the code that makes the request in a check for whether that value is true or false. I'd also add a bool that tells me whether I should even bother making a request--no sense in requesting if the last request came back empty (unless, perhaps, the data set could change since the last request). Either way, here's the code I'd start with:
( function( global )
{
var $ = global.jQuery,
$win = $( global ),
$doc = $( global.document ),
$ajaxLoader = $( 'div#ajaxloader' ),
$main = $( '#main' ),
requestInProgress = false,
outOfPosts = false;
$win.scroll( function()
{
if( ! requestInProgress &&
! outOfPosts &&
$win.scrollTop() === $doc.height() - $win.height()
)
{
requestInProgress = true;
$ajaxLoader.show();
$.ajax( {
url: 'loader.php',
data: {
lastid: $( '.container:last' ).attr( 'id' )
},
success: function( html )
{
if( html )
{
$main.append( html );
$ajaxLoader.hide();
}
else
{
outOfPosts = true;
$ajaxLoader.html( 'No more posts to show.' );
}
},
complete: function()
{
requestInProgress = false;
}
} );
}
} );
}( window ) );