Page getting redirected before ajax completion - javascript

i use ajax to create a session and to redirect the page when the user clicks on a button like this .. im using this in the facebook api(using the api to create a session with the user.id)
FB.login(function(response) {
if (response.session) {
FB.api('/me', function(user) {
if (user!=null) {
var request = new XMLHttpRequest();
if(document.getElementById("ans2").value==""){
document.getElementById("belowbutton2").innerHTML ="Don't leave it blank!!";
}
else{
var request2 = new XMLHttpRequest();
request.onreadystatechange=function(){
if(request.readyState==4 && request.status==200){
document.getElementById("debugger").innerHTML = request.responseText;
window.location = "weekques/weekques.php";
}
}
var uid = user.id;
alert(uid);
var jqXHR = ($.ajax)({url:"sessions.php?uid="+uid,
async:false,
cache: false,
timeout: 30000,
error:function(){
window.location = "http://www.xyz.com";
},
success:function(){
request.open("GET", "weekques/answer.php?ans="+document.getElementById("ans2").value, true); //+"&qid="+qidjs
request.send();
}
});
}
}
});
}
});
but the problem is that the window is redirecting before the session is created ..
heres the
sessions.php file
<?php
session_start();
require_once("connection.php");
$user=mysql_query("SELECT * from `thebirbals`.`FBusers` where uid='$uid';");
$row_count=mysql_num_rows($result);
$_SESSION['uid']=$_GET["uid"];
$uid = $_SESSION['uid'] ;
if($row_count==1){
$_SESSION['name'] = $check["name"];
$_SESSION['profile_link'] = $check["profile_link"];
$_SESSION['dp'] = $check["dp"];
}
else{
require_once('facebook/src/facebook.php');
$facebook = new Facebook(array(
'appId' => '1550598824560526',
'secret' => '4cf28242b5abfa26be8fd3e2074e5724',
'cookie' => false
));
$fql = "SELECT first_name,profile_url,pic_small from user where uid=$uid";
$response = $facebook->api(array(
'method' => 'fql.query',
'query' =>$fql,
));
foreach($response as $val)
{
$_SESSION['name']=$val["first_name"];
$_SESSION['dp']=$val["pic_small"];
$_SESSION['profile_link']= $val["profile_url"];
$name = $val["first_name"];
$profile_link = $val["profile_url"];
$dp = $val["pic_small"];
echo "done";
}
$insert=mysql_query("INSERT INTO `thebirbals`.`FBusers` ( `uid`, `name`, `profile_link`, `dp`) VALUES ('$uid', '$name', '$profile_link', '$dp');");
}
?>
i want to redirect after the sessions.php is finished running this does not happen
ty in advance for any help .. :)

I took a stab. Not sure if this will fix your issue entirely, but take it as a starting point:
FB.login(function (response) {
if (response.session) {
FB.api('/me', function (user) {
if (user != null) {
if (document.getElementById("ans2").value == "") {
document.getElementById("belowbutton2").innerHTML = "Don't leave it blank!!";
}
else {
var uid = user.id;
alert(uid);
$.ajax({ url: "sessions.php?uid=" + uid,
async: false,
cache: false,
timeout: 30000,
error: function () {
window.location = "http://www.xyz.com";
},
success: function () {
$.get("weekques/answer.php", $.param({ "ans": document.getElementById("ans2").value }), function (data) {
alert("Answer received");
document.getElementById("debugger").innerHTML = data;
window.location = "weekques/weekques.php";
});
}
});
}
}
});
}
});

Related

How to re render a .ejs page with new data after ajax request

I need to re render my homepage.ejs with new data on the server side after an ajax request. I know you can (somehow) re render the elements in the ajax callback but I was wondering if I could just re render my homapage.ejs since I have if statements that look for vacations, and current_user variables to set the right partialview.ejs
my ajax method:
function user_login(email, password) {
var data = {};
data.email_login = email;
data.password_login = password;
var message_header = $("#message_header");
$.ajax({
url: "/sign_in",
method: 'POST',
data: data
}).done(function (res) {
if (!res.success) {
message_header.text("Incorrect email of password. Please try again.").css("color", "red");
$("#username_textfield").val("");
$("#password_textfield").val("");
}
if (res.success) {
console.log("user logged");
}
});
my server side (inside of a query callback)
get_all_vacations(function (error, vacations) {
if (error) {
console.log("error when getting vacations " + error);
response.json({ success: false });
} else {
request.session.vacations = vacations;
response.render('the_vacation.ejs', { vacations : vacations, current_user : new_current_user }, function() {
response.json({success : true});
console.log("in render method");
});
}
});
i tried this but it does not work.
response.render('the_vacation.ejs', { vacations: vacations, current_user: new_current_user });
I think the simplest way, based on how your code is written would be to use window.location.reload(); when the login is successful.
function user_login(email, password) {
var data = {};
data.email_login = email;
data.password_login = password;
var message_header = $("#message_header");
$.ajax({
url: "/sign_in",
method: 'POST',
data: data
}).done(function (res) {
if (!res.success) {
message_header.text("Incorrect email of password. Please try again.").css("color", "red");
$("#username_textfield").val("");
$("#password_textfield").val("");
}
if (res.success) {
console.log("user logged");
window.location.reload(); // <--- Cause the browser to reload the EJS
}
});

Append values automatically after facebook login is correct

I'm working on a cordova project and i'm using facebook login as one of the user authentication. The login works correctly but the issue is i have to press a button of an id getinfo before the values from facebook appear. But what i want to do is when the login is right the values should be appended automatically to the divs.
$(document).ready(function () {
$("#login").on('click', function (event) {
// Defaults to sessionStorage for storing the Facebook token
openFB.init({ appId: '000000000000000' });
// Uncomment the line below to store the Facebook token in localStorage instead of sessionStorage
// openFB.init({appId: 'YOUR_FB_APP_ID', tokenStore: window.localStorage});
openFB.login(
function (data) {
if (data.status === 'connected') {
$id = $("#id").append(data.id)
$name = $("#name").append(data.name)
$gender = $("#gender").append(data.gender)
$email = $("#email").append(data.email)
} else {
alert('Facebook login failed: ' + data.error);
}
});
});
});
how do i make my script work without using this below function
$(document).ready(function () {
$("#getinfo").on('click', function (event) {
openFB.api({
path: '/me',
success: function (data) {
console.log(JSON.stringify(data));
$id = $("#id").append(data.id)
$name = $("#name").append(data.name)
$gender = $("#gender").append(data.gender)
$email = $("#email").append(data.email)
document.getElementById("userPic").src = 'http://graph.facebook.com/' + data.id + '/picture?type=small';
},
error: errorHandler
});
});
});
Try this login function:
openFB.login(
function (data) {
if (data.status === 'connected') {
openFB.api({
path: '/me',
success: function (data) {
console.log(JSON.stringify(data));
$id = $("#id").append(data.id)
$name = $("#name").append(data.name)
$gender = $("#gender").append(data.gender)
$email = $("#email").append(data.email)
document.getElementById("userPic").src = 'http://graph.facebook.com/' + data.id + '/picture?type=small';
},
error: errorHandler
});
} else {
alert('Facebook login failed: ' + data.error);
}
});
});

How to return authRequired and WL.Server.invokeHttp value to client side using web services in Adapter based authentication with worklight?

Edit : I am using Adapter based authentication with worklight and angularJs. on click of login button i'm calling submitLogin procedure and pass the username and password in parameter as mention below. my query is after invocation of adapter how i'll return the authRequired value and WL.Server.invokeHttp(input) response simultaneously to the client side. i also mention challenge handler for authentication in login services code
adapter code:
function submitLogin(username, password){
WL.Logger.debug("username: "+username);
var payload = {
"Header": {
"header": {
"myschemeName": "",
"myserviceVersion": "0.00",
"myinternalId": "",
"myexternalId": "",
"mysource": "web",
"mydestination": "test",
"myuserId": ""
}
},
"Body": {
"login": {
"username": username,
"password": password
}
}
}
var input = {
method : 'post',
returnedContentType : 'jsonp',
path: '/mywebservices/login',
headers : {
'Accept-Encoding': 'gzip,deflate',
'Content-Type': 'application/json'
},
body: {
'contentType' : 'application/json',
'content' : payload
}
};
return {authRequired: false, WL.Server.invokeHttp(input);};
}
login services:
angular.module('my.services')
.factory('loginServices', function($http, $q, $rootScope) {
'use strict';
//worklight
var realm = "AdapterAuthRealm";
var securityTest = "Master-Password";
//offline
var offlineAuthed = false;
var tempUser = {};
//user object
var userObj = {};
//login popup
userObj.dialog = false;
//login error message
userObj.authError = "";
//logged in boolean
userObj.loggedIn = null;
var defunct = null;
//change handler
var ch = WL.Client.createChallengeHandler(securityTest);
//first response after protected call
ch.isCustomResponse = function(response){
console.log("challenge handler -- isCustomResponse");
if (!response || !response.responseJSON || response.responseText === null) {
return false;
}
if (typeof(response.responseJSON.authRequired) !== 'undefined'){
return true;
} else {
return false;
}
};
//when isCustomResponse returns true
ch.handleChallenge = function(response){
console.log("challenge handler -- handleChallenge");
var err = response.responseJSON.errorMessage;
var req = (String(response.responseJSON.authRequired) == "true");
if (!req){ //successful login request
console.log("-> login success!");
//create offline auth credentials
createOfflineAuth();
//call the success function of initial adapter call
//ch.submitSuccess();
}
//error message
userObj.authError = "";
if (err != null){
userObj.authError = "* " + err;
}
//login boolean
userObj.loggedIn = !req;
//show login popup
userObj.dialog = req;
//update scope
$rootScope.$apply();
//resolve original function if it exists
if (defunct != null){
defunct.resolve(userObj.loggedIn);
}
};
//** Offline **//
//check if user is online
function checkOnline(){
var def = $q.defer();
WL.Client.connect({
onSuccess: function(){
console.log("** User is online!");
def.resolve(true);
},
onFailure: function(){
console.log("** User is offline!");
def.resolve(false);
},
timeout: 1000
});
return def.promise;
}
//creates an offline authentication object
function createOfflineAuth(){
console.log("creating offline auth");
//encrypt the user object
var encyptedUser = md5(angular.toJson(tempUser));
//save to local storage
localStorage.setItem(tempUser.username, encyptedUser);
//clear tempUser
tempUser = {};
}
//offline login
function offlineLogin(){
userObj.authError = "";
//encrypt the tempuser object
var match = md5(angular.toJson(tempUser));
var savedAuth = localStorage.getItem(tempUser.username);
//check if matching the saved one
offlineAuthed = (savedAuth == match);
console.log("Login successfull: " + offlineAuthed);
//error - mismach
if (!offlineAuthed){
userObj.authError = "* Wrong login details.";
}
//error - if the user has never authenticated with the server
if (savedAuth == null){
userObj.authError = "* You have to go online first.";
}
//login boolean
userObj.loggedIn = offlineAuthed;
//show login popup
userObj.dialog = !offlineAuthed;
return offlineAuthed;
}
//-- APIS to the rest of the app --//
return {
getUser: function(){
return userObj;
},
initUser: function () {
console.log("-> getting user state data");
var def = $q.defer();
checkOnline().then(function (onl){
if (onl){ //online
WL.Client.updateUserInfo({onSuccess: function(){
userObj.loggedIn = WL.Client.isUserAuthenticated(realm);
def.resolve();
}});
} else { //offline
userObj.loggedIn = false;
def.resolve();
}
});
return def.promise;
},
checkUser: function () {
var def = $q.defer();
checkOnline().then(function (onl){
if (onl){ //online
userObj.loggedIn = WL.Client.isUserAuthenticated(realm);
} else { //offline
userObj.loggedIn = offlineAuthed;
}
userObj.dialog = !userObj.loggedIn;
//check success
if (!userObj.loggedIn){
//save the deferred for challengehandler
defunct = def;
} else {
//resolve
def.resolve(true);
}
});
return def.promise;
},
login: function (user,pass){
//promise
var logindef = $q.defer();
//tempuser
tempUser = {username:user, password:pass};
userObj.user = user;
checkOnline().then(function (onl){
if (onl){ //online
console.log("attempting online login");
var options = {
parameters:[user, pass],
adapter:"myAdapter",
procedure:"submitLogin"
};
ch.submitAdapterAuthentication(options,{
onSuccess: function(){
console.log("-> submitAdapterAuthentication onSuccess!");
//update user info, as somehow isUserAuthenticated return false without it
WL.Client.updateUserInfo({onSuccess: function(){
//return promise
logindef.resolve(true);
}});
}
});
} else { //offline
console.log("attempting offline login");
logindef.resolve(offlineLogin());
}
});
return logindef.promise;
}
};
});
I am trying to decrypt your question. It's not clear at all.
However there is already one thing that jumps out.
In your adapter you finished with:
return {authRequired: false, WL.Server.invokeHttp(input);};
You saying authRequired false even before checking if the credentials are valid?
You are supposed to parse the content of the results of WL.Server.invokeHttp(input) inside the adapter, decide if the credentials are valid.
If they are valid use setActiveUser before returning authRequired false.
Don't return the content of WL.Server.invokeHttp(input) to the client. This is meant for the adapter to parse.
See this tutorial: https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-1/foundation/authentication-security/adapter-based-authentication/

ajax validation login doesn't shows

I am using laravel 4 and I am trying to display login validation by using ajax. I have the following javascript validation:
jQuery('#form-signin').submit(function()
{
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: jQuery('#form-signin').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".validation-error-inline").hide();
}
})
.done(function(data)
{
$('#validation-login').empty()
if (data.validation_failed === 1)
{
var arr = data.errors;
alert(arr);
}
else {
window.location = data.redirect_to;
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
and in my userController:
public function doLogin() {
Input::flash();
$data = [
"errors" => null
];
if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')))) {
return Response::json(["redirect_to" => "/"]);
} else {
if (Request::ajax()) {
$response_values = array(
'validation_failed' => 1,
'errors' => 'Invalid username or password',
);
return Response::json($response_values);
}else
{
echo 'error';
}
}
}
The problem is that it always displays "error" message, which means that jaax request isn't performed. What is wrong?
In your doLogin() function try
return Response::json(array(
'validation_failed' => 1,
'errors' => 'Unknow error'
))
instead of
echo "error"

How to logout only my FBapplication not my facebook account?

I am using facebook javascript sdk on my web application. I am using graph api to login my application. When I logged out from my application, my application is logged out and my facebook account is also logout.
How to logout only my application not my facebook account ?
Please help me if someone has found solution for this.
Code:
<script type="text/javascript">
var button;
var userInfo;
window.fbAsyncInit = function() {
FB.init({ appId: '########',
status: true,
cookie: true,
xfbml: true,
oauth: true});
showLoader(true);
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
userdata = document.getElementById('user-data');
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
showLoader(true);
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
}, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function login(response, info){
if (response.authResponse) {
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
showLoader(false);
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
showLoader(false);
}
//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
showLoader(true);
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
showLoader(false);
});
}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish();
});
}
function share(){
showLoader(true);
var share = {
method: 'stream.share',
u: 'http://www.appovative.com/'
};
FB.ui(share, function(response) {
showLoader(false);
console.log(response);
});
}
function setStatus(){
showLoader(true);
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
showLoader(false);
}
);
}
function showLoader(status){
if (status)
document.getElementById('loader').style.display = 'block';
else
document.getElementById('loader').style.display = 'none';
}
</script>
Their is function defined in FB object use this to destroy FB session ,
usage( via PHP)
$facebook->destroySession();
Or
FB API provides a logoutURL which will log the user out of their current Facebook account.
you can use it like this ,
$facebook = new Facebook($config);
$params = array('next' => 'www.yousite.com/test.php' );
$logoutURL = $facebook->getLogoutUrl($params);
***note
advisable to add below codes also (not in case if you dont want your user to log out of your site)
//remove PHPSESSID from browser
if ( isset( $_COOKIE[session_name()] ) )
setcookie( session_name(), '', time()-7000000, '/' );
//clear session from globals
$_SESSION = array();
With JS using a custom event
ref : (FB.logout() called without an access token. javascript sdk)
function fbLogoutUser() {
FB.getLoginStatus(function(response) {
if (response && response.status === 'connected') {
FB.logout(function(response) {
document.location.reload();
});
}
});
}

Categories

Resources