5

I have a signup.php page that contains the login through facebook button. structure of page is something like this

<?php
if(!isset($_SESSION['logged_in']))
{
    echo '<div id="results">';
    echo '<!-- results will be placed here -->';
    echo '</div>';
    echo '<div id="LoginButton">';
    echo '<a href="#" rel="nofollow" class="fblogin-button" onClick="javascript:CallAfterLogin();return false;">Login with Facebook</a>';
    echo '</div>';
}
else
{
    echo 'Hi '. $_SESSION['user_name'].'! You are Logged in to facebook, <a href="?logout=1">Log Out</a>.';
}
?>

ajax code used on this page calls another page process_facebook.php and processes data at the backend. code used for ajax in signup.php page is

<script type="text/javascript">
window.fbAsyncInit = function() {
    FB.init({
        appId: '<?php echo $appId; ?>',
        cookie: true,xfbml: true,
        channelUrl: '<?php echo $return_url; ?>channel.php',
        oauth: true
        });
    };
(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 CallAfterLogin(){
    FB.login(function(response) {       
        if (response.status === "connected") 
        {
            LodingAnimate(); //Animate login
            FB.api('/me', function(data) {

              if(data.email == null)
              {
                    //Facbeook user email is empty, you can check something like this.
                    alert("You must allow us to access your email id!"); 
                    ResetAnimate();

              }else{
                    AjaxResponse();
              }

          });
         }
    },
    {scope:'<?php echo $fbPermissions; ?>'});
}

//functions
function AjaxResponse()
{
     //Load data from the server and place the returned HTML into the matched element using jQuery Load().
     $( "#results" ).load( "process_facebook.php" );
}

//Show loading Image
function LodingAnimate() 
{
    $("#LoginButton").hide(); //hide login button once user authorize the application
    $("#results").html('<img src="img/ajax-loader.gif" /> Please Wait Connecting...'); //show loading image while we process user
}

//Reset User button
function ResetAnimate() 
{
    $("#LoginButton").show(); //Show login button 
    $("#results").html(''); //reset element html
}

</script>

Now the issue is that the process_facebook.php page works with fb data at backend, and after that gets redirected back to signup.php page and displays the data that process_facebook.php page had printed(optional). What i want is that instead of redirecting from process_facebook.php page back to signup.php page and displaying its data, i wish to redirect to another page, not only the new data should get loaded from the new page but the url should also get changed.(i.e www.example.com/app/signup.php should change to www.example.com/app/profile.php)

i forgot to mention but i have tried using header() to redirect but it is simply fetching data of profile.php page but showing the www.example.com/app/signup.php url.. Now the problem in it is that if i refresh the page for any reason, then the data of old signup.php page gets loaded

Sam
  • 1,381
  • 4
  • 30
  • 70
  • Uhm, may be I'm missing something, but why you simply don't use header() function in your process_facebook.php? Check http://stackoverflow.com/questions/768431/how-to-make-a-redirect-in-php for more details. – Vick Jan 16 '15 at 12:41
  • header('Location: you_url_here'); Use this whenever you need to redirect through PHP – Murtaza Khursheed Hussain Jan 16 '15 at 13:48
  • @Vick i tried using header but instead of redirecting to another url it is fetching the data of the new profile page and showing the www.example.com/app/signup.php url. and if i reload the page then i am getting the data of old signup page – Sam Jan 16 '15 at 15:12
  • @MurtazaHussain i am not able to get the required data, plz read the comment that i have posted above – Sam Jan 16 '15 at 15:13
  • 1
    did you try using *window.location.href* after the ajax request is successful ? – bayblade567 Jan 16 '15 at 19:49
  • You can not use a Location header to redirect the browser in response to a request made via AJAX – AJAX is a _background_ request, and therefor can not redirect the page that the browser is currently displaying. As @bayblade567 said, you should use client-side JavaScript to redirect after the response to your AJAX request is received. – CBroe Jan 17 '15 at 00:03
  • @CBroe can you please tell me how i can do so – Sam Jan 17 '15 at 03:43
  • You use `window.location.href` by assigning the new address to it. If you need to redirect only under certain conditions, then return a value from your server-side script that allows your client-side JavaScript to make that decision. – CBroe Jan 17 '15 at 14:03

5 Answers5

1

Do one thing paste below function in your function file :-

function redirect($url=NULL)
{
    if(is_null($url)) $url=curPageURL();
    if(headers_sent())
    {
        echo "<script>window.location='".$url."'</script>";
    }
    else
    {
        header("Location:".$url);
    }
    exit;
}

And the call this function like :

redirect($url);

so when you will get the data from facebook so after apply the check on $user_profile you can redirect user via above function, this function will check if header already sent then it will use javascript else it will user Header().

Nilesh Chourasia
  • 408
  • 4
  • 11
0

Headers need to go at the top of the page, before any HTML is output to the client. You can also output the data as the server goes down the page "writing" the HTML to the client.

Before any HTML, but after opening PHP use this:

header('Location: http://www.example.com/');

Referr to: http://php.net/manual/en/function.header.php

a coder
  • 546
  • 4
  • 23
0

If I follow right, you're using Facebook for the user session and all the Facebook code you're using is Javascript so you want to use javascript to do the redirect...

document.location = '/profile.php';

That needs putting in place wherever the call to the back end completes.

Harry B
  • 2,864
  • 1
  • 24
  • 44
0

Just apply a die(); after your header call.

Jørgen R
  • 10,568
  • 7
  • 42
  • 59
Mumtaz Ahmad
  • 422
  • 5
  • 12
  • While this answers the question it’s always a good idea to put some text in your answer to explain what you're doing. Read [how to write a good answer](http://stackoverflow.com/help/how-to-answer). – Jørgen R Feb 26 '15 at 13:44
0

As Harry said, you are most certainly going to want to do this via JS.

document.location = '/profile.php';

function CallAfterLogin(){
    FB.login(function(response) {       
        if (response.status === "connected") 
        {
            LodingAnimate(); //Animate login
            FB.api('/me', function(FBdata) {

              if(FBdata.email == null)
              {
                    //Facbeook user email is empty, you can check something like this.
                    alert("You must allow us to access your email id!"); 
                    ResetAnimate();

              }else{
                    //you need to call some php script via ajax here to send these details to your server.
                    $.post('fbResponseParse.php',FBdata)
                    // your php should return some sort of an ok, or even a url for you to redirect to. 
                    //if it fails you need to display an error not redirect.
                      .done(function(data){
                       //data in this scope is the response from your php script. 
                          if(data.success) document.location = '/profile.php';
                          else displayError(data.errorMess)
                       })
              }

          });
         }
    },
    {scope:'<?php echo $fbPermissions; ?>'});
}

So what you are doing is using JS to talk to Facebook. Then upon that response you send it to your back end via AJAX. Your back end should parse the data, create the session details, most importantly though it sends you a success(bool) and errorMess (if applicable) then you use .done to parse the success/fail and render messages. This will keep the client here, on the signup page unless the facebook stuff is a success.

kripple
  • 151
  • 6