using ajax with javascript to put in database - javascript

I'm trying to put the infos into my database, for that, this code is in the connexion.jsp which is a page that ask to log with facebook.
the code is supposed to be called into the Controller which is a file in java, and go into the databse.
So my problem is the fact that the code $.ajax doesn't seems to work. It doesn't give a success or error window.alert with or without function(){}.
I might have missed some information about ajax, but i can't find more info about my error.
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
$.ajax({
method: 'post',
url: '/hello/facebookconnection',
first_name: response.first_name,
last_name: response.last_name,
email: response.email,
success:
//success: function(){
window.alert('Sent User data!')//;}
,
error:
window.alert('Error in sending ajax data')
});
else {
document.getElementById('status').innerHTML = 'User cancelled';
}
}, {scope: 'email'});
}

function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
$.ajax({
method: 'post',
url: '/hello/facebookconnection',
first_name: response.first_name,
last_name: response.last_name,
email: response.email,
success:
//success: function(){
window.alert('Sent User data!')//;}
,
error:
window.alert('Error in sending ajax data')
});
} else {
document.getElementById('status').innerHTML = 'User cancelled';
}
}, {scope: 'email'});
}
You have a syntax error in front of your else.

Related

Can't get facebook user's email using facebook javascript sdk

I'm using facebook authentication on my website using javascript sdk. I can get my email and name but I can't get their email, if they're loging in, only their name (it's my fb developer app).
It asks for the login, in case no one is logged in on facebook yet but get nothing happens. If I put an alert where it's supposed to login to my app and it indeed returns the name, just not the email. But if it's me I get both. Why's that?
Here's my code:
<%-- Facebook conection script--%>
<script src="//connect.facebook.net/en_US/all.js"></script>
<script> FB.init({
appId: '334351783684824',
cookie: true,
xfbml: true,
version: 'v2.8'
});
function fbAuthUser() {
FB.login(checkLoginStatus);;
}
function checkLoginStatus(response) {
if (response.status === 'connected') {
FB.api('/me', 'GET', { fields: 'email,name' }, function (response) {
alert(response.email + "; " + response.name);
Ajax(response.email, response.name);
});
}
}
function Ajax(expressao1, expressao2) {
var request = { email: expressao1, nome: expressao2 }
$.ajax({
url: 'login.aspx/LoginExterno',
method: 'post',
contentType: 'application/json',
data: JSON.stringify(request),
dataType: 'json',
success: function (resp) {
window.location.href = resp.d;
},
error: function () { }
})
}
</script>
It's supposed to login and, after getting the data, use that ajax function to access a code behind c# function that redirects the user to the index, if he/she already has an account or to the registry if he/she doesn't have one. It doesn't even go in the Ajax function, because the email parameter is undefined, probably. But when both are present it does.
So, how can I get the email?
Ok, I finally got it. On on FB.Login function, I need to add the scope and the user has to give permission. On my code, it would be like:
FB.login(checkLoginStatus,{scope: 'email'});;

Data is not going through the ajax code

I'm using Facebook login feature & transferring some variables to other page through ajax. This particular ajax code isn't working, data is not going through. However I've other ajax code in other pages that works pretty good.
I'm not able to find the defect in the code.
Here is the code:
Page where ajax is called
<script type='text/javascript'>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXX',
status : false,
cookie : true,
xfbml : true
});
}
function Login()
{
FB.login(function(response) {
if (response.authResponse)
{
getUserInfo();
}
else
{
console.log('User cancelled login or did not fully authorize.');
}
},{scope:'email,public_profile'});
}
function getUserInfo() {
FB.api('/me/permissions', function(response) {
var permission_response = JSON.stringify(response);
var permissions = eval('('+permission_response+')');
$.ajax({
type: "POST",
url: "/ajax_save_facebook_data.php",
data: {permissions:permissions},
success: function(option){
alert(option); // Nothing coming here, blank alert
}
});
});
}
AJAX Page
$permissions=$_POST['permissions'];
echo $permissions;
Anybody can help in this? I will really appreciate it.
FB.api is asynchrone function, so your var permissions doesn't exist when you do your ajax call.
Try:
function getUserInfo() {
FB.api('/me/permissions', function(response) {
var permission_response = JSON.stringify(response);
var permissions = eval('('+permission_response+')');
$.ajax({
type: "POST",
url: "/ajax_save_facebook_data.php",
data: {permissions:permissions},
success: function(option){
alert(option); // Nothing coming here, blank alert
}
});
});
}

jquery ajax call not returning as expected

I'm unsure why this jquery ajax call is failing. Basically, I want to authenticate and if the authentication is a success, do something.
I found this but the answer seems to abbreviated to be much use to me (is assumes you already know how to implement the solution). jQuery ajax return value
Here is my ajax call (I have stripped the fluff for getting the username/password):
function authenticate() {
$.ajax({ //TODO: Securely send this (ssl?)
type: 'POST',
url: 'includes/clientAuthenticate.php',
data: { username: username, password: password},
success:function(data){
if(data==='true') {
return "true";
} else {
return "User failed to log into the system.\nEmail request ignored.\n\nError message: \n" + data;
}
},
error:function(jqXHR, textStatus, errorThrown){
return "User failed to log into the system. Potential problem with server or connection.";
}
});
And I call it in this function:
function attemptEventSubmit(eKey) {
var authReturn = authenticate();
if(authReturn=="true") {
emailEvent(eKey);
} else {
alert(authReturn);
}
}
When it returns, it always alerts that authReturn is "undefined". I suspect it's defining authReturn as undefined because the authenticate function 'finishes' before the ajax call gets back...
But I'm not sure how to fix this problem.
I suspect I could call separate instead of returning values... (say, in this example, calling the emailEvent function directly in the ajax success function) but that would make the authenticate function specific... and it'd no longer be able to be used for authenticating for other purposes.
You can use your code but will need a callback. A better way would be look into promises.
function authenticate(onsuccess, onfail) {
$.ajax({ //TODO: Securely send this (ssl?)
type: 'POST',
url: 'includes/clientAuthenticate.php',
data: { username: username, password: password},
success:function(data){
onsuccess(data); // you should check if this is a function
},
error:function(jqXHR, textStatus, errorThrown){
onfail(errorThrown);
}
});
function attemptEventSubmit(eKey) {
authenticate(
function(ajaxData){
emailEvent('whatever you want to send');
},
function(errThrown){
alert(errThrown);
});
}
How about pass in a callback function as another argument of the function authenticate().
So the code changes will be
function authenticate(callback) {
$.ajax({ //TODO: Securely send this (ssl?)
type: 'POST',
url: 'includes/clientAuthenticate.php',
data: { username: username, password: password},
success:function(data){
if(data==='true') {
//return "true";
callback("true");
} else {
//return "User failed to log into the system.\nEmail request ignored.\n\nError message: \n" + data;
callback("User failed to log into the system.\nEmail request ignored.\n\nError message: \n" + data);
}
},
error:function(jqXHR, textStatus, errorThrown){
//return "User failed to log into the system. Potential problem with server or connection.";
callback("User failed to log into the system. Potential problem with server or connection.");
}
});
Calling the function authenticate will become:
function attemptEventSubmit(eKey) {
authenticate(function(authReturn){
if(authReturn=="true") {
emailEvent(eKey);
} else {
alert(authReturn);
}
});
}

how to post object to facebook user wall?

I am using Facebook JavaScript SDK, this code is for log in and post an object to user's wall, which returns an error,
{"error":{"message":"(#200) You do not have sufficient to permissions to perform this action","type":"OAuthException","code":200}}
FB.login(function(data){
if(data.authResponse){
facebookGetDetails();
}else{
console.log("Login operation aborted");
}
},{scope: 'email,publish_actions,read_stream'});
FB.api(
'/me',
'post',
{
app_id: xxxxxxxxxxxx,
type: "business.business",
url: url,
title: title,
image: picUrl,
contact_data: "Bangalore, India",
location: "17.024522",
description: desc
},
function(response) {
console.log(JSON.stringify(response));
// handle the response
});
the following code works, but it only posts to activity stream, not to wall.
FB.api(
'me/namespace:review',
'post',
{
business: "http://samples.ogp.me/616004095080596"
},
function(response) {
// handle the response
}
);
I guess you're using a incomplete endpoint URL here
FB.api(
'/me',
...
);
You should call /me/feed with a post request as described here: https://developers.facebook.com/docs/graph-api/reference/user/feed/#publish

Cakephp Ajax Login is loggin in even with wrong data

I have a simple html form to login outside my cake structure, I send the login data via jquery to my login function:
public function login() {
if ($this->request->is('ajax')) {
$this->request->data['Appuser']['password'] = Security::hash($this->request->data['password']);
$this->request->data['Appuser']['name'] = $this->request->data['name'];
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl(array('action' => 'returnUserData')));
}else{
$this->response->body(json_encode('Login failed!'));
}
}elseif($this->request->is('post')){
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}else{
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
The very strange thing is:
the login via post from /view/users/login.ctp form works perfectly!
When I try to login from "outside" via ajax, I am always logged in even with wrong access details and get the data from function 'returnUserData'
$('#login').click(function() {
$.ajax({
type: "POST",
url: '/api/login',
data: {
name: $("#username").val(),
password: $("#password").val()
},
success: function(data)
{
alert(data);
}
});
});
When I set a debug(); after if ($this->request->is('ajax')) I can see it, so the script seems to go into the right if section. But I don't get it, why the $this->Auth->login always return true...?

Categories

Resources