Does it make sense to redirect by calling a separate page?

This is a logout page triggered by a jquery post through a button.

The logout script is simply

<?php

session_start();

session_destroy();

header("Location: new location");

?>

When navigating to this page by url, it works, session is destroyed, page is redirected. But when calling it by a jquery post

<script>
$.post("logout.php");
</script>

Nothing happens, it could be that the jquery post request isn't working.

I'm just wondering if there is no point to doing it this way.

Upvotes: 0

Views: 46

Answers (2)

Krishna .M
Krishna .M

Reputation: 85

header("Location: new location");

This PHP code of course redirects when it is loaded as a file. But then, when it comes to

<script>
$.post("logout.php");
</script>

This is an AJAX request. AJAX Request is the one that just requests a page and responds the HTML contents of the page. Therefore, the header() function doesn't redirect the page in which the <script> lies.

Instead of $.post you might want to use $.ajax

$.ajax
{
 url: 'logout.php',
 type: 'POST',
 contentType: false,
 processData: false,
 success: function(){
  window.location='new location';
 }
}

Hope this helps. Thank you.

Upvotes: 0

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34160

First of all use $.get instead of $.post as it is much faster.

This is a logout page triggered by a jquery post through a button.

header("Location: new location");

will cause the logout.php itself to redirect and only will change the returning reslut and won't redirect the caller page itself.

try like:

<script>
$.get('logout.php', function(){ documnt.location.href='/index.php' });
</script>

this will redirect to the page you want after ajax is excuted.

Upvotes: 2

Related Questions