I am using facebook login and its graph api to list all images of user to my website and the following code is working fine only for me that is the administrator and owner of the facebook app, it is not working for anyother person when he logged in the website using facebook login.
Explanation of code: When user logged in, a function named testAPI is called which gets user basic information and then it makes another call to FB.API for permission access and then finally for getting pictures.
The permission parameter "res" gets nothing for anyother user, but its working for me(administrator).
heres the code:
<div id="fb-root"></div>
<script>
// Additional JS functions here
window.fbAsyncInit = function() {
FB.init({
appId : MY_APP_ID, // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
login();
} else {
login();
}
});
};
function login() {
FB.login(function(response) {
if (response.authResponse) {
testAPI();
} else {
// cancelled
}
},{scope:'user_photos',perms:'user_photos'});
}
var id;
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
console.log(response);
id=response.id;
var link='/'+ id + '/permissions?access_token=FB_GENERATED_ACCESS_TOKEN';
FB.api(link,function(res){
console.log("permissons: ",res);
link='/'+ id + '/photos?fields=images';
FB.api(link, function(response) {
//placing all pictures
for(var i=0;i<response.data.length;i++)
{
var img="<img src="+response.data[i].images[0].source+" class='small' />";
$("#images").append(img);
}
console.log(response);
});
});
});}
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script></body>
<fb:login-button autologoutlink='true'
perms='email,user_birthday,status_update,publish_stream'></fb:login-button>
<div id="images"></div>
I got your actual problem,
<fb:login-button autologoutlink='true'
perms='email,user_birthday,status_update,publish_stream'></fb:login-button>
You missing out here , user_photos permission. your javascript function is not calling because fb:login-button do all stuff by self. your new code should be :
<fb:login-button autologoutlink='true'
perms='email,user_birthday,status_update,publish_stream,user_photos'></fb:login-button>
Instead of
var link='/'+ id + '/permissions?access_token=FB_GENERATED_ACCESS_TOKEN';
FB.api(link,function(res){
console.log("permissons: ",res);
link='/'+ id + '/photos?fields=images';
FB.api(link, function(response) {
//placing all pictures
for(var i=0;i<response.data.length;i++)
{
var img="<img src="+response.data[i].images[0].source+" class='small' />";
$("#images").append(img);
}
console.log(response);
});
Try this:
FB.api('/me/permissions', function (response) {
console.log("permissons: ", res);
var perms = response.data[0];
if (perms.user_photos) {
FB.api('/me/photos?fields=images', function (response) {
//placing all pictures
for (var i = 0; i < response.data.length; i++) {
var img = "<img src=" + response.data[i].images[0].source + " class='small' />";
$("#images").append(img);
}
console.log(response);
} else {
// User DOESN'T have permission. Perhaps ask for them again with FB.login?
login();
}
});
Related
I have a problem about how to get a response from another website using php (api.php) but it works if api.php is placed in my folder where ( Index.php ) is also. Is it possible to get the responses from other pages like ( myurl.com/api.php ). Sorry for my bad english.
ajax placed from index.php
<script title="ajax do checker">
function enviar() {
var linha = $("#lista").val();
var linhaenviar = linha.split("\n");
var total = linhaenviar.length;
var ap = 0;
var rp = 0;
linhaenviar.forEach(function(value, index) {
setTimeout(
function() {
$.ajax({
url: 'api.php?lista=' + value,
type: 'GET',
async: true,
success: function(resultado) {
if (resultado.match("#Aprovada")) {
removelinha();
ap++;
aprovadas(resultado + "");
}else {
removelinha();
rp++;
reprovadas(resultado + "");
}
$('#carregadas').html(total);
var fila = parseInt(ap) + parseInt(rp);
$('#cLive').html(ap);
$('#cDie').html(rp);
$('#total').html(fila);
$('#cLive2').html(ap);
$('#cDie2').html(rp);
}
});
}, 500 * index);
});
}
function aprovadas(str) {
$(".aprovadas").append(str + "<br>");
}
function reprovadas(str) {
$(".reprovadas").append(str + "<br>");
}
function removelinha() {
var lines = $("#lista").val().split('\n');
lines.splice(0, 1);
$("#lista").val(lines.join("\n"));
}
code where the response will appear
<h6 style="font-weight: bold;" class="card-title">Declined - <span id="cDie2" class="badge badge-danger">0</span></h6>
<div id="bode2"><span id=".reprovadas" class="reprovadas"></span>
api.php
enter link description here
full code for index.php enter link description here
I'm working on an app where I get a json via an ajax call. This json contains objects where you get a certain status code per extension (1 = online, 2, is ringing, 3 = busy)
How can I ensure that the value that I get back is converted to the text (preferably with a different color of the )
So when I get a 1 back I want it to show Online, and with a 2 Ring etc
$.ajax({
type:'GET',
url: url,
dataType: 'json',
error: function(jqXHR, exception) {ajax_error_handler(jqXHR, exception);},
success: function(data){
// console.log(JSON.parse(data.responseText));
// console.log(JSON.parse(data.responseJSON));
console.log(data['entry']);
var event_data = '';
$.each(data.entry, function(index, value){
/* console.log(data['entry']);*/
event_data += '<tr>';
event_data += '<td>'+value.extension+'</td>';
event_data += '<td>'+value.status+'</td>';
<!--event_data += '<td>'+value.registration+'</td>';-->
event_data += '</tr>';
});
$("#list_table_json").append(event_data);
},
error: function(d){
/*console.log("error");*/
alert("404. Please wait until the File is Loaded.");
}
});
Thanks in advance!
I have change the code
function get_blf() {
$.ajax({
type:'GET',
url: url,
dataType: 'json',
error: function(jqXHR, exception) {ajax_error_handler(jqXHR, exception);},
success: function(data){
$.each(data.entry, (index, value) => {
const tableRow = document.createElement('tr');
const tdExtension = document.createElement('td');
extension.textContent = value.status;
const tdStatus = document.createElement('td');
if (value.status == 3) status.textContent = 'Busy';
if (value.status == 2) status.textContent = 'Ringing';
if (value.status == 1) status.textContent = 'Online';
tdStatus.classList.add(`status-${value.status}`);
tableRow.appendChild(tdExtension);
tableRow.appendChild(tdStatus);
$('#list_table_json').append(tableRow);
}
});
}
}
and add the css, but now i can't get any values back. but now i can't get any values back. (sorry I'm fairly new to javascript)
Please use the DOM API
One way of getting colors would be to use CSS classes for the status:
// js
...
$.each(data.entry, (index, value) => {
const tableRow = document.createElement('tr');
const tdExtension = document.createElement('td');
extension.textContent = value.extension;
const tdStatus = document.createElement('td');
if (value.status == 3) status.textContent = 'Busy';
if (value.status == 2) status.textContent = 'Ringing';
if (value.status == 1) status.textContent = 'Online';
tdStatus.classList.add(`status-${value.status}`);
tableRow.appendChild(tdExtension);
tableRow.appendChild(tdStatus);
$('#list_table_json').append(tableRow);
});
...
// css
.status-1 {
color: green;
}
.status-2 {
color: red;
}
.status-3 {
color: orange;
}
I finally got the script working. I am now trying to build in a polling, however I see that the ajax call is executed again and the array is fetched. However, the table is not refreshed but a new table is added, does anyone know a solution for this?
code I'm using now for the repoll is
function repoll(poll_request, poll_interval, param=null) {
if (poll_interval != 0) {
if (window.timeoutPool) {
window.timeoutPool.push(setTimeout(function() { poll_request(param); }, poll_interval));
}
else {
setTimeout(function() { poll_request(param); }, poll_interval);
}
}
else {
log_msg('Poll cancelled.');
}
}
tableRow.appendChild(tdExtension);
tableRow.appendChild(tdNr);
tableRow.appendChild(tdStatus);
$('#list_table_json').append(tableRow);
});
repoll(get_blf, poll_interval_blf);
My website reads QR CODES using the mobile phone. I have used that library
https://github.com/schmich/instascan
<div class="select">
<label for="videoSource">Video source: </label><select id="videoSource"></select>
</div>
<video autoplay muted playsinline></video>
<script async src="js/main.js"></script>
Because the mobile phone has many camaras I want to let the user to select which camara wants for scanning the qr code.
main.js:
https://simpl.info/getusermedia/sources/
https://github.com/samdutton/simpl/blob/gh-pages/getusermedia/sources/js/main.js
'use strict';
var videoElement = document.querySelector('video');
var videoSelect = document.querySelector('select#videoSource');
videoSelect.onchange = getStream;
getStream().then(getDevices).then(gotDevices);
function getDevices() {
// AFAICT in Safari this only gets default devices until gUM is called :/
return navigator.mediaDevices.enumerateDevices();
}
function gotDevices(deviceInfos) {
window.deviceInfos = deviceInfos; // make available to console
console.log('Available input and output devices:', deviceInfos);
for (const deviceInfo of deviceInfos) {
const option = document.createElement('option');
option.value = deviceInfo.deviceId;
if (deviceInfo.kind === 'videoinput') {
option.text = deviceInfo.label || `Camera ${videoSelect.length + 1}`;
videoSelect.appendChild(option);
}
}
}
function getStream() {
if (window.stream) {
window.stream.getTracks().forEach(track => {
track.stop();
});
}
const videoSource = videoSelect.value;
const constraints = {
video: {deviceId: videoSource ? {exact: videoSource} : undefined}
};
return navigator.mediaDevices.getUserMedia(constraints).
then(gotStream).catch(handleError);
}
function gotStream(stream) {
window.stream = stream; // make stream available to console
videoSelect.selectedIndex = [...videoSelect.options].
findIndex(option => option.text === stream.getVideoTracks()[0].label);
videoElement.srcObject = stream;
}
function handleError(error) {
console.error('Error: ', error);
}
Then I want to start the scanner to the camara the user has selected because I want to obtaint the QR-CODE:
<script type="text/javascript">
let scanner = new Instascan.Scanner({ video: document.getElementById('preview'),mirror: false });
scanner.addListener('scan', function (content) {
alert("qr result " + content);
});
Instascan.Camera.getCameras().then(function (cameras) {
if (cameras.length > 0) {
scanner.start(cameras[0]); //I want to scanner.start the camara that the user has selected.
} else {
console.error('No cameras found.');
}
}).catch(function (e) {
console.error(e);
});
</script>
I get this JSON from DeviceNewController
public function index(Request $request)
{
$device_new = Device_new::with(['device']);
return Device_new::all()->toJson();
}
And when I wrote AJAX in view blade, it show me data from DB in console.
<script>
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
console.log(newdev.responseText);
};
newdev.send();
</script>
But I need to pass it in Leaflet script and write all data on map (coordinates, markers, device info)
When I set all in one script, there is no data in console, I can not fix it.
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
var coordinates = newdev.responseText;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
};
};
newdev.send();
Did i make a mistake somewhere, is this correct???
You miss understood Ajax. Ajax is a function from JQuery, a JS library.
The ajax() method is used to perform an AJAX (asynchronous HTTP) request.
You have to add the JQuery library to your source, then you can create a Ajax call.
https://www.w3schools.com/jquery/ajax_ajax.asp
$.ajax({url: "/devices_new", success: function(result){
//result = JSON.parse(result); // If your result is not a json Object.
var coordinates = result;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
}
},
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}});
});
I make it on this way, and its working.
<script>
$(document).ready(function() {
$.ajax({
/* the route pointing to the post function */
url: '/device_new',
type: 'GET',
data: {
message: $(".getinfo").val()
},
dataType: 'json',
/* remind that 'data' is the response of the AjaxController */
success: function(data) {
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(map);
}
}
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
</script>
I hope someone will help me.
I have an API which is implemented with JSON web-services. I want to implement Login. A user is created and I need to have login the user. That is when I enter username and password it must log the user in .
I have read the tutsplus tutorial, but I am unable to authenticate the user. Can anyone help me out.
Here is the code I am using:
// create tab group
var tabGroup = Titanium.UI.createTabGroup();
var win1 = Titanium.UI.createWindow({
title:'Login',
backgroundColor:'#fff'
});
var username = Ti.UI.createTextField({
top:'10%',
borderRadius:3,
hintText:'username',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
width:'80%',
height:'auto',
left:'10%',
right:'10%',
touchEnabled: true,
});
win1.add(username);
var pass = Ti.UI.createTextField({
top:'30%',
borderRadius:3,
hintText:'password',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
width:'80%',
height:'auto',
left:'10%',
right:'10%',
touchEnabled: true,
passwordMask: true
});
win1.add(pass);
var loginBtn = Titanium.UI.createButton({
title:'Login',
top:'50%',
width:'60%',
height:'15%',
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:14}
});
win1.add(loginBtn);
var url = 'http://qudova.com/api.php?function=AuthenticateUser&u=ns.nadeem.m#gmail.com&p=qudovatest';
var json;
var loginReq = Titanium.Network.createHTTPClient();
loginBtn.addEventListener('click',function(e)
{
if (username.value != '' && pass.value != '')
{
// Here I will get the Token (asdfasdf....)
loginReq.open("GET",url);
authstr = 'Basic ' +Titanium.Utils.base64encode(username.value +':' +pass.value);
loginReq.setRequestHeader('Authorization', authstr);
loginReq.send();
}
else
{
alert("Username/Password are required");
}
});
loginReq.onload = function()
{
var jsonObject = JSON.parse(this.responseText);
// Here I have made a check if the Token is returned successfully it will alert the user that he authenticated
if (jsonObject.Token == "asdfadsfasdfadsf")
{
alert("Authenticated");
}
else
{
alert("response.message");
}
};
win1.open();
Thanks in Advance. Is my concept clear ?
You get a JSON array as response. So you should access jsonObject[0].Token.
// create tab group
var tabGroup = Titanium.UI.createTabGroup();
var win1 = Titanium.UI.createWindow({
title:'Login',
backgroundColor:'#fff'
});
var username = Ti.UI.createTextField({
top:'10%',
borderRadius:3,
hintText:'username',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
width:'80%',
height:'auto',
left:'10%',
right:'10%',
touchEnabled: true,
});
win1.add(username);
var pass = Ti.UI.createTextField({
top:'30%',
borderRadius:3,
hintText:'password',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
width:'80%',
height:'auto',
left:'10%',
right:'10%',
touchEnabled: true,
passwordMask: true
});
win1.add(pass);
var loginBtn = Titanium.UI.createButton({
title:'Login',
top:'50%',
width:'60%',
height:'15%',
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:14}
});
win1.add(loginBtn);
var url = 'http://qudova.com/api.php?function=AuthenticateUser&u=ns.nadeem.m#gmail.com&p=qudovatest';
var json;
var loginReq = Titanium.Network.createHTTPClient();
loginBtn.addEventListener('click',function(e)
{
if (username.value != '' && pass.value != '')
{
// Here I will get the Token (asdfasdf....)
loginReq.open("GET",url);
authstr = 'Basic ' +Titanium.Utils.base64encode(username.value +':' +pass.value);
loginReq.setRequestHeader('Authorization', authstr);
loginReq.send();
}
else
{
alert("Username/Password are required");
}
});
loginReq.onload = function()
{
var jsonObject = JSON.parse(this.responseText);
// Here I have made a check if the Token is returned successfully it will alert the user that he authenticated
if (jsonObject[0].Token === "asdfadsfasdfadsf")
{
alert("Authenticated");
}
else
{
alert("response.message");
}
};
win1.open();
Alternatively you can change your backend implementation, that the result will be an object instead of an array.
Nevertheless you should change your backend because at the moment it's possible to authenticate via plain GET parameters.