1

I am making a logout button which calls a PHP script via an AJAX call but somehow my php is not redirecting. Also when I try to use javascript it doesnt work either.

I tried the following things:

  • Adding ob_start() and ob_end_flush()
  • Changing exit; to exit();
  • Changing header("Location: http://localhost/page_login.html) to echo("<script>location.href = http://localhost/page_login.html';</script>");

When I open the php script directly in my URL (by just typing it in) it redirects me to the page.login.html however from the ajax call its not. When I print the data it prints the page_login.html file which also excludes the option that its not in the correct map.

Anyone any ideas on how to fix this?

HTML

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="logout_button">
Logout
</div>
<script src="jquery-3.2.1.js"></script>
<script src="logout.js" type="text/javascript"></script>
</body></html>

JAVASCRIPT (logout.js)

$('#logout_button').click(function(){
        $.ajax({
            type: 'POST',
            url: 'logout.php',
            error: function(response) { console.log(JSON.stringify(response))},

            success: function(data){
                console.log(data);
            }
        });
})

PHP (logout.php)

<?php
header('Location: http://localhost/page_home.html');
exit;
?>
5
  • Whoops that was just a typo by me writing this example code. This was not the problem. The PHP script still does not redirect Commented Feb 1, 2018 at 15:05
  • 1
    Are you expecting that when you when you you make an AJAX call, that the page that makes that call is being redirected? Because that is not how it works. Only the ajax call itself is redirected and the result you get will be the page it is redirected to. Commented Feb 1, 2018 at 15:10
  • Yes I except that I am on one page (say the home page) and I click on the logout button. The home page should then redirect to the login page. How would you suggest me to be redirected then, accordingly to the logout situation I described? Commented Feb 1, 2018 at 15:13
  • Have you set apache ( or other ) to serve PHP scripts with html extension or are the pages you mention above all php scripts with .php extension? What are you using to maintain the user session? I see no session_start nor anything to teardown the session in logout.php Also- the logout page is not sending a response so the ajax callback is never going to do anything as such Commented Feb 1, 2018 at 15:13
  • 2
    @user3262578 I'm not sure why you use AJAX here in the first place. Just surround a submit button with a form tag with the form tag attributes method="POST" and action="logout.php" Commented Feb 1, 2018 at 15:15

3 Answers 3

2

You have a misunderstanding of how AJAX is working in this situation. When you're performing an AJAX call, a separate request is being sent as your POST to the given URL. This does not inherently affect the original page you are on in the client window. Essentially, what is happening is:

  1. A user clicks 'logout'
  2. The server (i.e. not the client's web browser) is sending a request to your logout.php
  3. logout.php runs its code and returns a response to your original page (success/fail in this case; or some data if you had a return in your PHP page)

The AJAX here is only a means of sharing information between the two pages, not to run them in succession. What you need to do is redirect the original page, and you can do this with JavaScript! After all, don't forget that JavaScript is our client-side language, with PHP being the server-side one.

There are any number of ways to redirect in JavaScript which you can find. For example, you may use window.location.href in this case:

$('#logout_button').click(function(){
    $.ajax({
        type: 'POST',
        url: 'logout.php',
        error: function(response) { console.log(JSON.stringify(response))},

        success: function(data){
            window.location.href = "http://localhost/page_home.html";
            console.log(data);
        }
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

I was writing this answer at the same time others were writing & submitting theirs (imagine that!) and while the answer to the question is similar, I don't think the others explained the fundamental gap in knowledge in the same way that I did. Seems like you're nit-picking.
Yes although some overlapping with the other answers a good clarification for me! I happy that you commented on my post. Thanks
I like your answer but I find it overkill to use AJAX in this case. A simple form submit would have the same result.
That is true; I got caught up in the assumption that OP was using AJAX for a specific reason, which is why I pointed out logic or a return in the second PHP page would be passed back. A simple HTML form submit or even cutting out the AJAX and using window.location.href would suffice.
2

Use location.href in Javascript inside ajax to redirect or reload, not in .php file

$('#logout_button').click(function(){
        $.ajax({
            type: 'POST',
            url: 'logout.php',
            dataType: "json",
            error: function(response) { console.log(JSON.stringify(response))},

            success: function(data){
                location.href = "/page_home.html";
                //console.log(data);
            }
        });
});

Also send response data from .php to logout/session destroy, like

<?php
   // Code here to logout or session destroy
   // return json or string 
   $response["success"] =  true;
   echo json_encode($response);
?>

2 Comments

OK. So if I understand correctly I call the logout.php file in which is stated session_destroy() and in javascript I redirect the page? I though this would be unsafe security wise.
@user3262578 : there is no security issue to use like this, you can just use all sensitive code in server side(PHP) and just return/echo json type data to redirect or reload page.
2

When you call directly your php file, header('Location: http://localhost/page_home.html'); add Location field to the HTTP Header that tell the browser to redirect the user to the specified location. If you call it via ajax, jQuery doesn't care about this header field. What you need is :

$('#logout_button').click(function(){
    //Insert your ajax call here if you need to do something server side like destroy the session 
    window.location.replace('http://localhost/page_home.html');
})

EDIT: As mentionned in the comments, it will be simpler to use a link to your logout.php with the header('Location: http://localhost/page_home.html'); in it.

3 Comments

Is this security wise ok to do?
In that case why not just use an anchor tag. Security wise it doesn't really matter. You might want to submit it as a POST though, so spiders wont scroll it and users can't accidentally link to it.
@user3262578 like Ivar, I think there isn't problem with security

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.